Mas*_*sha 3 c# inheritance abstract-class automatic-properties
我有以下3个课程:
public class BaseProperty1{
public string Property1 {get; set;}
}
public class ChildProperty1 : BaseProperty1 {
}
public abstract class Base{
public abstract BaseProperty1 bp1 {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试从Base派生以下类:
public class Child : Base{
public ChildProperty1 bp1 {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
但是我收到的错误是"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; }
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用泛型来解决问题:
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; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2060 次 |
最近记录: |