• Advertisement
Sign in to follow this  

[.net] [Resolved]Using System.Reflection to clone any class

This topic is 4398 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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]

Share this post


Link to post
Share on other sites
Advertisement
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;
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement