c# - 在 C# 中,从实际上充满子项的 List<Parent> 中,如何访问这些子项的特定构造函数?

标签 c# types constructor

首先,我有这样的东西:

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/

相关文章:

c# - 从 Fileupload 控件在标签中发布文件名 - ASP.NET 4.0 C#

c# - BNF 语法有没有结尾的部分?

asynchronous - 异步方法中的类型不匹配

java - 对于集合,我们什么时候更喜欢使用 Object 类型,什么时候使用原始类型

c++ - long long 初始化和 8 字节平台

c++ - move 赋值运算符和 move 构造函数之间的区别?

c# - 在 C# 中从另一个主体调用一个构造函数

c# - 如何在后面的代码中使字符串加粗

c# - 实现依赖对象子属性的自定义集合的正确方法?

javascript - 将 props 传递给子组件