Interface inheritance: is extending properties possible?

后端 未结 7 1204
庸人自扰
庸人自扰 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-04 00:05

    I had this conversation with a couple of our Lead Devs at my work, and the conclusion that we came to is that:

    • Either way technically works.
    • Interfaces are all about singular purpose.

    An Interface is used to define a way that any inheriting class can act. Even if your second interface shares pieces, or is even used in some of the same conditions, an interface is defined to explain how to use a class in ALL conditions related to that interface.

    Additionally, classes are able to inherit multiple interfaces for this very reason. In terms of code clarity:

    public class SomeClass : IInherited, IBase
    

    The line above explicity states that SomeClass is capable of doing the actions of IInherited, and the actions of IBase, and it does not matter that some of those actions are the same. Having to crawl backwards through the interfaces to discover that IInherited extends IBase could be confusing to other developers that may look at your code in the future.

    It may seem like a duplication of effort having the same values in both interfaces, but there are no assumptions made in the function of your code.

提交回复
热议问题