从基类创建派生类的实例 [英] Create an instance of derived class from the base class

查看:35
本文介绍了从基类创建派生类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的抽象基类A:

public abstract class A : ICloneable {

    public int Min { get; protected set; }
    public int Max { get; protected set; }

    public A(int low, int high)
    {
        this.Min = low;
        this.Max = high;
    }

    //...

    public object Clone()
    {
        return new this(this.Min, this.Max); //<-- ??
    }
}

由我的班级B扩展而来:

public class B : A
{
    public B(int low, int high) : base(low, high) { }

    //...
}

由于A是抽象的,它不能被实例化,但派生类可以.是否可以从 A 类创建一个 B 类的新实例?

Since A is abstract, it cannot be instantiated, but the derived class can. Is it possible to, from class A, create a new instance of class B?

假设类A有很多派生类,它怎么知道实例化哪一个?

Suppose class A has many derived classes, how will it know which one to instantiate?

好吧,我想实例化我当前的 A 相同的类(或类型).

Well, I want to instantiate the same class (or type) my currently A is.

也就是说,如果我从 B 类调用 Clone 方法,我想实例化一个新的 B.如果我从 C 类调用 Clone 方法,我想实例化一个新的 C.

That is, if I'm calling the Clone method from a class B, I want to instantiate a new B. If I'm calling the Clone method from a class C, I want to instantiate a new C.

我的方法是这样写:

return new this(this.Min, this.Max);

但这似乎不起作用,也无法编译.

But that doesn't seem to work nor compile.

是否可以在 C# 中完成此操作?

Is it possible to accomplish this in C#?

如果不是,是否有解释以便我理解?

If it isn't, is there an explanation so I can understand?

推荐答案

虽然我喜欢 Jamiec 解决方案,但我缺少使用反射的脏解决方案 :)

While I like Jamiec solution, I'm missing dirty solution using reflection :)

public class A {
  public object Clone() {
    var type = GetType().GetConstructor(new[] { typeof(int), typeof(int) });
    return type.Invoke(new object[] { this.Min, this.Max });
  }
}

这篇关于从基类创建派生类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆