[.net] [Resolved]Using System.Reflection to clone any class
Hey, got a quick question
Lets say I have a class, clsObjClass which has the variables A, B and C. Using System.Reflection, how could I clone 2 classes from it?
Example,
NewClass = New clsObjClass
NewClass.A = OtherClass.A
NewClass.B = OtherClass.B
etc
How can I use System.Reflection to fill it's variables with the values in the other class?
Thanks in advance :)
[Edited by - CadeF on April 5, 2006 10:12:14 AM]
Something like this should work (not tested, actual syntax may vary slightly):
public object Clone(object o){ Type t = o.GetType(); object clone = Activator.CreateInstance(t); foreach(FieldInfo fi in t.GetFields()) { fi.SetValue( clone, fi.GetValue(o) ); } return clone;}
you know. all your programming problems would be solved a lot quicker and easier, if you would just clone Arlid [grin]
Memberwise clone creates a shallow copy, which is probably useful in some circumstances (for example things that don't change), but I find it annoying that my references all point to the same object. While this is good for memory consumption, if you actually go to modify something for just that newly cloned object, then you actually modify both that object and every other "object" that is referenced by the same location. Most of the time a deep copy is what is needed.
By the way.
Reflection is usually pretty slow.
You would probably do better (performance wise) to write a code generator (using reflection if you want to) to create the code that does the clone.
It does a search through kind of an internal database to find types and variables and so forth.
Make sure that you setup your filter to reject a lot of the junk that you don't care about when using reflection.
Reflection is usually pretty slow.
You would probably do better (performance wise) to write a code generator (using reflection if you want to) to create the code that does the clone.
It does a search through kind of an internal database to find types and variables and so forth.
Make sure that you setup your filter to reject a lot of the junk that you don't care about when using reflection.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement