只读接口,不需要抽象类中的主体?

bfo*_*ops 1 c# abstract-class interface

我希望能够在实例化类中可写的接口中创建只读属性,但是如果继承通过抽象类,我遇到了问题:

interface IFoo {
    string Foo { get; }
}

abstract class Bar : IFoo {
}

class Baz : Bar {
    public string Foo { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误Bar does not implement interface member IFoo.Foo.有没有办法绕过这个?我希望最终实例化的类确定setter的可见性.

Bri*_*128 5

你需要实现它抽象:

abstract class Bar : IFoo
{
    public abstract string Foo { get; }
}
Run Code Online (Sandbox Code Playgroud)

但是,当您执行此操作时,您可以选择覆盖Baz类中的可见性.

您可以做的最好是在派生类中使用支持字段:

class Baz : Bar
{
    private string _foo;
    public override string Foo
    {
        get { return _foo; }
    }
}
Run Code Online (Sandbox Code Playgroud)

关于重复问题的答案详细说明了原因.问题源于这样一个事实:属性getter和setter是抽象的,而不是属性本身.