In Schulungen werde ich immer wieder gefragt ob es in .net eine ähnliche Kopier Funktion für Objektinstanzen gibt wie in Java, C++. Nein, die gibt es leider nicht. Ein Workaround ist der Klasse eine eigene Copy Funktion zu spendieren mit der das Objekt dann sich selbst serialisiert und deserialsiert:
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters
Imports System.Runtime.Serialization.Formatters.Binary
Public Enum Gender
Female
Male
End Enum
<Serializable()> _
Public Class Human
# Region "datamember"
Private m_preName As String
Private m_lastName As String
Private m_dob As DateTime
Private m_sex As Gender
# End Region
# Region "eigenschaften"
Public Property FirstName() As String
Get
Return Me.m_preName
End Get
Set(ByVal Value As String)
Me.m_preName = Value
End Set
End Property
Public Property LastName()
Get
Return Me.m_lastName
End Get
Set(ByVal Value)
Me.m_lastName = Value
End Set
End Property
Public Property DateOfBirth() As DateTime
Get
Return Me.m_dob
End Get
Set(ByVal Value As DateTime)
Me.m_dob = Value
End Set
End Property
Public Property Sex() As Gender
Get
Return Me.m_sex
End Get
Set(ByVal Value As Gender)
Me.m_sex = Value
End Set
End Property
# End Region
# Region "konstruktoren"
Public Sub New()
End Sub
# End Region
Public Function Info() As String
Return "Datentyp: " & Me.GetType().ToString() & vbCrLf & Me.m_lastName & " " & Me.m_preName
End Function
Public Function Copy() As Human
Dim result As Human
Dim formatter As New BinaryFormatter
Dim memStream As New MemoryStream
formatter.Serialize(memStream, Me)
memStream.Position = 0
result = CType(formatter.Deserialize(memStream), Human)
memStream.Close()
formatter = Nothing
Return result
End Function
End Class |