初学vb.net ,总结一下byval和byref
1 通过byval传递的变量,vb.net会复制与源值相等的一个新的变量。而byref则相当于引用。
例如我们学习c的时候得swap()函数
imports system
test that cant swap a and b
class myapp
public shared sub main()
dim a as integer = 0
dim b as integer = 1
console.writeline("source: a" & a & "b"& b)
fakeswap(a,b) after this fakeswap(a,b), a still is 0 and b still is 1
console.writeline("after fakeswap: a" & a & "b"& b)
swap(a,b) after this swap(a,b), a is 1 and b is 0
console.writeline("after swap: a" & a & "b"& b)
end sub
fake swap function:fakeswap()
shared sub fakeswap(byval ina as integer, byval inb as integer)
dim tmp as integer
tmp = ina
ina = inb
inb = tmp
end sub
real swap function :swap()
shared sub swap(byref ina as integer, byref inb as integer)
dim tmp as integer
tmp = ina
ina = inb
inb = tmp
end sub
end class
2 注意的是: 如果byval传递的是自定义的类的一个实例,被复制的只是该实例的引用,引用所指向的资源并没有被复制。–相当于c++中的浅拷贝。
imports system
类a的实例mya作为函数 testa(byval ina as a)的参数,结果应该是
–按值传递为浅拷贝,只是复制了一份引用–a的实例mya和 ina共享一个资源
class myapp
public shared sub main()
dim mya as a
console.writeline("the original resource of mya is: " & mya.resource)
call testa()
testa(mya)
console.writeline("after call the byval fun , the resource of mya is: " & mya.resource)
end sub
函数testa() 将mya按值传递进去为ina 修改ina的resource ,实际上修改的也是mya的resource
shared sub testa(byval ina as a)
ina.resource = 1
end sub
end class
类a 有资源 resource (integer)
class a
public resource as integer = 0
end class
3 如果想实现类的实例(不是引用)的“按值“传递(深拷贝),则必须overridde clone()方法 ?还是专门有拷贝构造函数?
方法一:
<serializable>_
class abc
xxx
end class
然后用memorystream和binaryformatter(streamcontext要用file类型的),这样绝对是深拷贝。但是如何实现c++中的“拷贝构造”呢?
待续…
