[英]Inherit from abstract class with properties of another type (.NET 3.5, C#)
我有以下3個課程:
public class BaseProperty1{
public string Property1 {get; set;}
}
public class ChildProperty1 : BaseProperty1 {
}
public abstract class Base{
public abstract BaseProperty1 bp1 {get; set;}
}
我正在嘗試從Base派生以下類:
public class Child : Base{
public ChildProperty1 bp1 {get; set;}
}
但是我收到的錯誤是“set”和“get”方法沒有實現。 它只是我正在使用的語法或我的思維方式是錯誤的嗎?
謝謝!
您將無法使用自動屬性,因為您必須完全匹配基類的類型。 你必須采用老式的方式:
public abstract class Child : Base
{
private ChildProperty1 _bp1;
public BaseProperty1 bp1
{
get { return _bp1; }
// Setter will be tricky. This implementation will default to null
// if the cast is bad.
set { _pb1 = value as ChildProperty1; }
}
}
您也可以使用泛型來解決問題:
public abstract class Parent<TProp> where TProp : BaseProperty1
{
public abstract T bp1 { get; set; }
}
public abstract class Child : Parent<ChildProperty1>
{
public ChildProperty1 bp1 { get; set; }
}
如果將方法或屬性標記為抽象 ,則必須在繼承的類中實現它。 您可以隱藏舊屬性(Base類中的bp1)並使用另一種返回類型編寫新屬性,如下所示:
public abstract class Base{
public BaseProperty1 bp1 {get; set;} //without abstract identifier
}
public class Child : Base
{
public new ChildProperty1 bp1 { get; set; } // with new modifier
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.