首先,我有这样的东西:
class Parent
{
int x;
public Parent(int _x)
{
x = _x
}
}
class Child1: Parent
{
int y;
public Child1(int _y):base(_y)
{
y=_y;
}
}
class Child2: Parent
{
int z;
public Child2(int _z):base(_z)
{
z=_z;
}
}
一个简单的父子层次结构。然后,我有一个实际上充满了 Child1 和 Child2 的列表。我想为列表中的每个对象制作副本,我想首先制作一个新项目作为副本。
但是,如果我这样做:
foreach(Parent p in list)
dictionaryOfCopies.Add(p, new Parent(p.x));
那么字典将充满Parent的,而不是Children1和Children2。有没有一种方法可以在不知道对象的特定类型的情况下调用类型化为其父类型的对象的构造函数?
最佳答案
一种方法是实现 ICloneable
interface在你的对象上,让每个实例克隆自己。
class Parent : ICloneable
{
int x;
public Parent(int _x)
{
x = _x
}
public virtual object Clone()
{
return new Parent(x);
}
}
class Child1 : Parent
{
int y;
public Child1(int _y) : base(_y)
{
y = _y;
}
public override object Clone()
{
return new Child1(y);
}
}
class Child2 : Parent
{
int z;
public Child2(int _z) : base(_z)
{
z = _z;
}
public override object Clone()
{
return new Child2(z);
}
}
然后,你会像这样使用它:
foreach(Parent p in list)
{
dictionaryOfCopies.Add(p, p.Clone() as Parent);
}
说到底,我所看到的对 ICloneable
接口(interface)的批评之一是它不是类型安全的。如果这让您感到厌烦,您仍然可以采用相同的想法,但实现您自己的 Clone
方法版本,该方法返回 Parent
而不是 object
.
关于c# - 在 C# 中,从实际上充满子项的 List<Parent> 中,如何访问这些子项的特定构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11940250/