Interface inheritance: is extending properties possible?

后端 未结 7 1207
庸人自扰
庸人自扰 2021-02-03 23:32

I want to do this:

interface IBase
{
    string Property1 { get; }
}

interface IInherited : IBase
{
    string Property1 { get; set; }
}

So th

7条回答
  •  渐次进展
    2021-02-03 23:51

    If the fact that the only way to do this is by using the new keyword bothers you, then in my opinion you're thinking about interfaces wrong.

    Sure, you could say that IInherited "inherits from" IBase; but what does that really mean? These are interfaces; they establish code contracts. By hiding the IBase.Property1 property with new string Property1 { get; set; }, you are not shadowing any functionality. Thus the traditional reason that a lot of developers consider hiding to be a "bad" thing -- that it violates polymorphism -- is irrelevant in this case.

    Ask yourself: what really matters when it comes to interfaces? They provide a guarantee of responding to certain method calls, right?

    So, given the following two interfaces:

    interface IBase
    {
        string Property1 { get; }
    }
    
    interface IInherited : IBase
    {
        new string Property1 { set; }
    }
    
    1. If an object implements IBase, you can read its Property1 property.
    2. If an object implements IInherited, you can read its Property1 property (just as with an IBase implementation), and you can also write to it.

    Again, there's really nothing problematic here.

提交回复
热议问题