Interface inheritance: is extending properties possible?

后端 未结 7 1275
庸人自扰
庸人自扰 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条回答
  •  Happy的楠姐
    2021-02-04 00:05

    You can either mark the property with the "new" keyword, or you can skip the inheritance:

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

    Or:

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

    Either way, this should work:

    public class SomeClass : IInherited, IBase
    {
        public string Property1
        {
            get
            {
                // ...
            }
            set
            {
                // ...
            }
        }
    }
    

    You may want to think hard before you make an inheritance chain for your interfaces, though. Who is going to see which interface? Would you need to cast to IInherited when passed an IBase? If so, can you be guaranteed that you can do that cast (if you allow user created classes, then the answer is no)? This kind of inheritance can really hurt (re)usability if you're not careful.

提交回复
热议问题