Clone a generic class in a compact framework solution...

M

Mobileboy36

Hello Group,

How do I take a clone of a generic class in Compact Framework?
Let's say I want to clone a sorted list: SortedList As SortedList(Of
Integer, Customer)

I constructed a class like this:
Public Class ClonableAndSortedCustomerList
Inherits SortedList(Of Integer, Customer)

Public Function Clone() As ClonableAndSortedCustomerList
Return DirectCast(Me.MemberwiseClone,
ClonableAndSortedCustomerList)
End Function
End Class

Using clone method realy cloned the list, but the items in the list where
not cloned.
Changing an item in the orininal list, caused the same change in the
'cloned' list.
So: my conclusion: I need another (correct) way to clone my generic class.

In the full framework it can be realised at this way:
(http://forums.microsoft.com/msdn/sh...tid=2208691&sb=0&d=1&at=7&ft=11&tf=0&pageid=1)
Public Class ObjectCloner
Public Shared Function Clone(Of T)(obj As T) As T

Using buffer As New MemoryStream()

Dim formatter As New BinaryFormatter()

formatter.Serialize(buffer, obj)

buffer.Position = 0

Dim temp As T = DirectCast(formatter.Deserialize(buffer), T)

Return temp

End Using

End Function

End Class

But how to realise it in VB.NET, using a compact framework solution?



Best regards,

Mobile boy
 
A

Andrew Brook

Hi,

does something like the following not work?

Public Class ObjectCloner
Public Shared Function Clone(obj As Object) As Object
Dim buffer As New MemoryStream()
Dim formatter As New BinaryFormatter()
formatter.Serialize(buffer, obj)
buffer.Position = 0
Return formatter.Deserialize(buffer)
End Function
End Class

Apologies if it errors or doesn't work, I haven't tested it :)

ta,
Andrew
 
G

Ginny Caughey [MVP]

Andrew,

The CF has no BinaryFormatter class out of the box, although I believe there
are 3rd party products that provide this capability.
 
A

Andrew Brook

hehe, ok, I guess that would cause problems then. How about implementing
IClonable on all the custom classes and making sure it doesn't do a
'shallow' copy of any member variables?

Andrew
 
G

Ginny Caughey [MVP]

Andrew,

I think you'd have to implement your own cloning logic, whether that
involved writing your own binary formatter or using Xml, which of course
would be bulkier.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top