-
Nov 8th, 2012, 07:38 PM
#1
Thread Starter
Member
Is this the proper way to deep clone a class?
This seems to work, but is it the best way to implement a deep clone?
Code:
Public Class Person
Public Property name() As String
Public Property numbers As List(Of Integer)
Public Function MakeACopy() As Person
Dim newone As Person
newone = DirectCast(Me.MemberwiseClone(), Person)
newone.numbers = New List(Of Integer)
For i = 0 To Me.numbers.Count - 1
newone.numbers.Add(Me.numbers(i))
Next
Return newone
End Function
End Class
Module Module1
Sub Main()
Dim Aperson As New Person
Aperson.name = "Alpha"
Aperson.numbers = New List(Of Integer)
For i = 1 To 5
Aperson.numbers.Add(i)
Next
Dim Bperson As New Person
Bperson = Aperson.MakeACopy
Bperson.name = "Beta"
Console.WriteLine(Aperson.name & ":" & Bperson.Name)
Bperson.numbers.Clear()
For i = 6 To 10
Bperson.numbers.Add(i)
Next
For i = 0 To 4
Console.WriteLine(Aperson.numbers(i).ToString & ":" & Bperson.numbers(i).ToString)
Next
Console.Read()
End Sub
End Module
-
Nov 8th, 2012, 08:11 PM
#2
Re: Is this the proper way to deep clone a class?
To answer the question: No, there is no "proper way" to deep clone a class. If there was one proper way, it would be possible to create a compiler that did it right every time.
You can do a bit better than what you have, since you could use List.AddRange rather than iterating through each item, but that's a pretty minor quibble. You could also do things other than the MemberwiseClone, but whether or not they would be better is hard to say.
My usual boring signature: Nothing
-
Nov 8th, 2012, 08:51 PM
#3
Re: Is this the proper way to deep clone a class?
The way he is doing it here is pretty much to only way to do a deep copy. Only difference is I'd use AddRange like you suggested and I'd call the method Clone not MakeACopy.
-
Nov 9th, 2012, 03:45 AM
#4
Re: Is this the proper way to deep clone a class?
I've never done this so can't provide code but I have seen code where you serialize it and then copy the binary stream. The benefit of doing it that way is that it should work on any serializable object without any knowledge of its structure. I believe it's quicker as well but, like I said, I've never done it so don't take my word for it. A quick google will find plenty of examples for you.
The best argument against democracy is a five minute conversation with the average voter - Winston Churchill
Hadoop actually sounds more like the way they greet each other in Yorkshire - Inferrd
-
Nov 9th, 2012, 04:27 AM
#5
Thread Starter
Member
Re: Is this the proper way to deep clone a class?
Thanks guy, I think I"m finally getting the hang of this oop stuff.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|