在覆盖添加制定者的属性 [英] Adding setters to properties in overrides

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

问题描述

为什么不允许更改属性的getter和setter方法的可见性和存在实现一个接口的时候?



 接口IFoo的
{
串酒吧{搞定; }
}

类RealFoo:IFoo的
{
公共RealFoo(串吧)
{
this.Bar =栏;
}

公共字符串酒吧{搞定;私人集; }
}

类StubFoo:IFoo的
{
公共字符串酒吧{搞定;组; }
}



...而不是法律实施一个抽象类时做同样的?

 抽象类AbstractFoo:IFoo的
{
公共抽象的字符串酒吧{搞定; }
}

类RealFoo:AbstractFoo
{
公共RealFoo(串吧)
{
this.Bar =栏;
}

//无法替换,因为酒吧不具有可重写的set访问
公众覆盖字符串酒吧{搞定;私人集; }
}


解决方案

在接口声明什么是公共属性类必须有(这只是一个合同)。这意味着你需要有这些属性,但可以添加到它们。



抽象类声明这些属性的实际结构。所以,如果你没有在抽象基二传手,你不能当你写override修饰符,它看起来在基类的东西覆盖添加到它在执行。结果


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.

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.

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

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