[英]Create an instance of derived class from the base class
我有我的抽象基類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#中實現這一目標?
如果不是,是否有解釋所以我能理解?
是的,這可以通過基類上的抽象工廠方法實現
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);
}
}
雖然我喜歡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 });
}
}
這可以完成,您當前的方法是一個定義良好的設計模式,但大多數實現使Clone
成為一個抽象的虛方法,並在所有子類中覆蓋它。
public abstract class A
{
public abstract A Clone( );
}
public class B : A
{
public override A Clone( )
{
return new B( );
}
}
public class C : A
{
public override A Clone( )
{
return new C( );
}
}
由於您使用的是C#,因此可以使用Activator
類。 您可以使用默認實現將Clone
方法設為虛擬(不是=== abstract)。
public abstract class A
{
public virtual A Clone( )
{
// assuming your derived class contain a default constructor.
return (A)Activator.CreateInstance(this.GetType( ));
}
}
編輯 -如果在所有派生類中沒有默認的無參數構造函數,則可以向Activator.CreateInstance
方法添加參數
(A)Activator.CreateInstance(this.GetType( ), this.Min, this.Max);
對於派生類型的不同構造函數,我建議您專門為這些類型重寫Clone
方法,而不是使用Clone
的默認實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.