将 setter 添加到覆盖中的属性 [英] Adding setters to properties in overrides

查看:28
本文介绍了将 setter 添加到覆盖中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why is it allowed to change the visibility and existence of getters or setters in a property when implementing an interface?

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; }
}

...在实现抽象类时这样做不合法吗?

...and not legal to do the same when implementing an abstract class?

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; }
}

推荐答案

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

The interface declares what public properties the class must have (It's just a contract). Which means you need to have those properties, but can add to them.

抽象类声明了这些属性的实际结构.因此,如果抽象库中没有 setter,则无法在实现中添加它.
当您编写覆盖修饰符时,它会在基类中查找要覆盖的内容.

The abstract class declares the actual structure of those properties. So if you don't have the setter in the abstract base, you can't add to it in the implementation.
When you write the override modifier it looks in the base class for something to override.

这篇关于将 setter 添加到覆盖中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆