I want to copy all things in a class to another

59 views Asked by At

I've found many solutions similar with my question. but they are not perfect for me. Here's what I want to do. *Modified : I will not use Reflection. totally slow.. so i am trying another method to work it out.

[System.Serializable]
class myBase
{
   public int a;
   public int nType;
   // Actually lots of fields and properties are here.
}
[System.Serializable]
class TypeA : myBase
{
   public int c;
}
[System.Serializable]
class TypeB : myBase
{
   public int d;
}

And here what I am trying.

class test
{
   public void test()
   {
          myBase cBase = new myBase();
          cBase.a = 100;
          cBase.nType = 0;
          if(cBase.nType == 0)
          {
             TypeA newThing = new TypeA();
             // I want to assign cBase to newThing.
             newThing = cBase as TypeA; <= it is not proper:( will return null.
          }         
          else 
          {
             TypeB newThing = new TypeB();
             newThing = test.DeepClone<myBase>(cBase); // it's also not proper XD.
          }     

          public static T DeepClone<T>(T obj)
          {
              using (MemoryStream ms = new MemoryStream())
              {
                  BinaryFormatter formatter = new BinaryFormatter();
                  formatter.Serialize(ms, obj);
                  ms.Position = 0;

                  return (T) formatter.Deserialize(ms);
              }
          }
}

I've not came up with any good solution for that issue.

If myBase class has a few variables, i will copy each of them one by one. However so many vars are in myBase class :(

1

There are 1 answers

2
n00b On

You can use a library AutoMap for this purpose.

https://github.com/AutoMapper/AutoMapper

But if you like to implement your own, you can use reflection to iterate through properties and set them in destination.

https://msdn.microsoft.com/en-us/library/z919e8tw.aspx

When doing so, you should remember that reflection is slow, so once you got the properties of source & destination objects, probably you should Cache that for future use.

This article is showing how you can also 'dynamic' type for this purpose. It claims that performance is much better http://weblogs.asp.net/gunnarpeipman/performance-using-dynamic-code-to-copy-property-values-of-two-objects