Mat*_*ero 4 c# oop inheritance abstract-class instantiation
我有我的抽象基类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); //<-- ??
}
}
Run Code Online (Sandbox Code Playgroud)
我的B级扩展了哪个:
public class B : A
{
public B(int low, int high) : base(low, high) { }
//...
}
Run Code Online (Sandbox Code Playgroud)
由于A是抽象的,因此无法实例化,但派生类可以.是否可以从A类创建B类的新实例?
假设类A有许多派生类,它将如何知道实例化哪一个?
好吧,我想实例化我目前A的同一个类(或类型).
也就是说,如果我打电话Clone从一个类的方法乙,我想实例化一个新的乙.如果我打电话Clone从一个类的方法ç,我想实例化一个新Ç.
我的方法是写一些类似于:
return new this(this.Min, this.Max);
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用也不编译.
是否有可能在C#中实现这一目标?
如果不是,是否有解释所以我能理解?
是的,这可以通过基类上的抽象工厂方法实现
public abstract class A
{
public int Min { get; protected set; }
public int Max { get; protected set; }
public A(int low, int high)
{
this.Min = low;
this.Max = high;
}
protected abstract A CreateInstance(int low, int high);
public object Clone()
{
return this.CreateInstance(this.Min,this.Max);
}
}
public class B:A
{
public B(int low, int high)
: base(low,high)
{
}
protected override A CreateInstance(int low, int high)
{
return new B(low,high);
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我喜欢Jamiec解决方案,但我缺少使用反射的肮脏解决方案:)
public class A {
public object Clone() {
var type = GetType().GetConstructor(new[] { typeof(int), typeof(int) });
return type.Invoke(new object[] { this.Min, this.Max });
}
}
Run Code Online (Sandbox Code Playgroud)