【发布时间】: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。 -
您介意提供现有解决方案“不适合您”的标准吗?您展示的示例是深度克隆的标准方法之一(使用带有反射的序列化作为实现细节) - 所以不清楚它是否是您认为不好的方法的示例,您认为是新颖的方法还是其他方法。跨度>