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

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

问题描述

我有我的抽象基类的 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); //<-- ??
    }
}



这是由我的课堂延伸的

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

    //...
}

由于 A 是抽象的,它不能被实例化,但在派生类可以。
是否有可能,从类的 A ,创建类的新实例的

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.

也就是说,如果我打电话克隆从类方法的,我想实例化一个新的
如果我从一个类中调用克隆方法的 C ,我想实例化一个新的 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#

如果不是这样,是有一个解释,所以我能理解?

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天全站免登陆