In .Net you do not have to do any cloning any more - you can simply serialise the object and then copy it into the target object. The technique is quite widely used and described - but it is interesting to use it with generics, as it means that you can use it anywhere in your application. Here is a code sample showing what to do:
Expand|Select|Wrap|Line Numbers
- Public Function CloneObject(Of T)(ByVal obj As T) As T
- Try
- Dim stream As New MemoryStream(1024)
- Dim formatter As New BinaryFormatter()
- formatter.Serialize(stream, obj)
- stream.Seek(0, SeekOrigin.Begin) ' go back to the start
- CloneObject = DirectCast(formatter.Deserialize(stream), T) 'get new object
- stream.Close() ' clear down the memory
- Catch excGeneric As Exception
- ReportException(excGeneric)
- End Try
- End Function
Expand|Select|Wrap|Line Numbers
- <Serializable()> Friend Class ChargeUnitType
Expand|Select|Wrap|Line Numbers
- Dim objClonedType As ChargeUnitType = CloneObject(ChargeUnitType)
Expand|Select|Wrap|Line Numbers
- Friend Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
- MyBase.New(info, context)
- End Sub