c# - 将 setter 添加到覆盖中的属性

标签 c# properties abstract

为什么在实现接口(interface)时允许更改属性中 getter 或 setter 的可见性和存在性?

interface IFoo
{
    string Bar { get; }
}

class RealFoo : IFoo
{
    public RealFoo(string bar)
    {
        this.Bar = bar;
    }

    public string Bar { get; private set; }
}

class StubFoo : IFoo
{
    public string Bar { get; set; }
}

...在实现抽象类时做同样的事情是不合法的?

abstract class AbstractFoo : IFoo
{
    public abstract string Bar { get; }
}

class RealFoo : AbstractFoo
{
    public RealFoo(string bar)
    {
        this.Bar = bar;
    }

    // Cannot override because 'Bar' does not have an overridable set accessor
    public override string Bar { get; private set; }
}

最佳答案

接口(interface)声明类必须具有哪些公共(public)属性(这只是一个约定)。这意味着您需要拥有这些属性,但可以添加到它们。

抽象类声明了这些属性的实际结构。所以如果你没有抽象基类中的setter,你就不能在实现中添加它。
当您编写覆盖修饰符时,它会在基类中查找要覆盖的内容。

关于c# - 将 setter 添加到覆盖中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6058352/

相关文章:

Java-静态变量,但扩展子类不共享该值

c++:如何避免 static_cast?

c# - 创建 View 时出错,通过反射调用的方法抛出未捕获的异常

c# - 从用于外部登录身份验证的 Twitter API 获取用户的电子邮件 ASP.NET MVC C#

c# - Owin,在身份验证请求中传递自定义查询参数

python - 设置属性不起作用 - 愚蠢的语法错误?

objective-c - 访问数组中的元素 - 请求非结构或联合中的成员

c# - 单元测试时使用反射或属性?

java - 执行从抽象类派生的子类的静态 block

c# - Firebird 数据库上的错误 MaxPoolSize