我有以下 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; }
}
关于c# - 从具有另一种类型属性的抽象类继承(.NET 3.5,C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6034132/