在C#中将setter添加到虚拟属性

Jam*_*ran 9 .net c# properties automatic-properties

我有这样的情况:

public abstract class BaseClass 
{
   public abstract string MyProp { get; }
}
Run Code Online (Sandbox Code Playgroud)

现在,对于某些派生类,属性值是一个合成值,因此没有setter:

public class Derived1 : BaseClass
{
    public override string MyProp { get { return "no backing store"; } }
}
Run Code Online (Sandbox Code Playgroud)

这很好用.但是,某些派生类需要更传统的后备存储.但是,无论我如何编写它,如在自动属性上,或使用显式的后备存储,我都会收到错误:

public class Derived2 : BaseClass
{
    public override string MyProp { get; private set;}
}

public class Derived3 : BaseClass
{
    private string myProp;
    public override string MyProp 
    { 
        get { return myProp;} 
        private set { myProp = value;}
    }
}
Run Code Online (Sandbox Code Playgroud)

Derived2.MyProp.set':无法覆盖,因为'BaseClass.MyProp'没有可覆盖的set访问器

我如何让它工作?

Bra*_*ith 11

你可以做的最好的事情是实现属性virtual而不是abstract.使getset块每扔NotSupportedException在基类和派生类中重写相应的行为:

public virtual string MyProp {
    get {
        throw new NotSupportedException();
    }
    set {
        throw new NotSupportedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您忘记在派生类中实现它,那么这不会为您提供编译时消息.您可以在摘要中实现get和set,并在派生类中显式实现,以显示它已被考虑. (2认同)