【问题标题】:I want to copy all things in a class to another我想将一个类中的所有内容复制到另一个类
【发布时间】:2015-06-17 03:25:45
【问题描述】:

我找到了许多与我的问题类似的解决方案。 但它们对我来说并不完美。 这就是我想做的。 *修改:我不会使用反射。完全慢..所以我正在尝试另一种方法来解决它。

[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;
}

这是我正在尝试的。

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);
              }
          }
}

我还没有为这个问题想出任何好的解决方案。

如果 myBase 类有几个变量,我会一一复制它们。 但是 myBase 类中有这么多变量:(

【问题讨论】:

  • 不是cBase as TypeA(),是cBase as TypeA
  • 您介意提供现有解决方案“不适合您”的标准吗?您展示的示例是深度克隆的标准方法之一(使用带有反射的序列化作为实现细节) - 所以不清楚它是否是您认为不好的方法的示例,您认为是新颖的方法还是其他方法。跨度>

标签: c# class deep-copy


【解决方案1】:

您可以为此目的使用库 AutoMap。

https://github.com/AutoMapper/AutoMapper

但是如果你想实现你自己的,你可以使用反射来遍历属性并将它们设置在目标中。

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

这样做时,你应该记住反射很慢,所以一旦你得到源和目标对象的属性,你可能应该缓存它以备将来使用。

这篇文章展示了您如何也可以为此目的使用“动态”类型。它声称性能要好得多 http://weblogs.asp.net/gunnarpeipman/performance-using-dynamic-code-to-copy-property-values-of-two-objects

【讨论】:

  • 我想自己实现,不会使用反射。我用反射实现了它,效果很好。但很慢。这就是为什么我需要另一种方式来做到这一点。
  • 如果您经常复制相同的对象,那么反射的缓存将会产生很大的不同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
相关资源
最近更新 更多