VB.Net的ByVal和ByRef --ByVal時(shí)的淺拷貝和深拷貝
2024-07-10 13:01:16
供稿:網(wǎng)友
初學(xué)vb.net ,總結(jié)一下byval和byref
1 通過(guò)byval傳遞的變量,vb.net會(huì)復(fù)制與源值相等的一個(gè)新的變量。而byref則相當(dāng)于引用。
例如我們學(xué)習(xí)c的時(shí)候得swap()函數(shù)
imports system
'test that can't 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傳遞的是自定義的類的一個(gè)實(shí)例,被復(fù)制的只是該實(shí)例的引用,引用所指向的資源并沒(méi)有被復(fù)制。--相當(dāng)于c++中的淺拷貝。
imports system
' 類a的實(shí)例mya作為函數(shù) testa(byval ina as a)的參數(shù),結(jié)果應(yīng)該是
' --按值傳遞為淺拷貝,只是復(fù)制了一份引用--a的實(shí)例mya和 ina共享一個(gè)資源
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
' 函數(shù)testa() 將mya按值傳遞進(jìn)去為ina 修改ina的resource ,實(shí)際上修改的也是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 如果想實(shí)現(xiàn)類的實(shí)例(不是引用)的“按值“傳遞(深拷貝),則必須overridde clone()方法 ?還是專門(mén)有拷貝構(gòu)造函數(shù)?
方法一:
<serializable>_
class abc
xxx
end class
然后用memorystream和binaryformatter(streamcontext要用file類型的),這樣絕對(duì)是深拷貝。但是如何實(shí)現(xiàn)c++中的“拷貝構(gòu)造”呢?
待續(xù)...