【发布时间】:2014-09-29 13:42:26
【问题描述】:
我有我的抽象基类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 的新实例?
假设类A有很多派生类,它怎么知道要实例化哪一个?
好吧,我想实例化我当前的 A 是相同的类(或类型)。
也就是说,如果我从一个类 B 调用 Clone 方法,我想实例化一个新的 B。
如果我从类 C 调用 Clone 方法,我想实例化一个新的 C。
我的方法是这样写:
return new this(this.Min, this.Max);
但这似乎既不工作也不编译。
是否有可能在 C# 中实现这一点?
如果不是,是否有解释让我能理解?
【问题讨论】:
-
这不能回答你的问题,但你为什么不使用 this.MemberwiseClone() 代替?
-
我不知道 MemberwiseClone() 方法,但我只是希望副本是一个新实例,具有相同的构造函数参数。 MemberwiseClone 可能做的任何其他处理都是无用的
-
如果
Bconstrutor 再增加一个参数呢? -
我希望这不会发生
标签: c# oop inheritance abstract-class instantiation