我找到了许多类似于我的问题的解决方案。但它们对我来说并不完美。这就是我想要做的。 *修改:我不会使用反射。完全慢..所以我正在尝试另一种方法来解决它。
[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类中有很多变量:(
您可以使用库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