VB.Net的ByVal和ByRef --ByVal时的浅拷贝和深拷贝

类别:.NET开发 点击:0 评论:0 推荐:

初学VB.Net ,总结一下ByVal和ByRef

1 通过ByVal传递的变量,VB.Net会复制与源值相等的一个新的变量。而ByRef则相当于引用。
例如我们学习C的时候得Swap()函数

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传递的是自定义的类的一个实例,被复制的只是该实例的引用,引用所指向的资源并没有被复制。--相当于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++中的“拷贝构造”呢?
待续...

本文地址:http://com.8s8s.com/it/it43827.htm