开发者

Interface inheritance and the new keyword

开发者 https://www.devze.com 2023-02-18 08:19 出处:网络
I want: public interface IBase { MyObject Property1 { get; set; } } public interface IBaseSub<T> : IBase

I want:

public interface IBase
{
    MyObject Property1 { get; set; }
}

public interface IBaseSub<T> : IBase
{
    new T Property1 { get; set; }
}

public class MyClass : IBaseSub<YourObject>
{
    public YourObject Property1 { get; set; }
}

But this doesn't compile. It gives th开发者_StackOverflow社区e error:

//This class must implement the interface member IBase.Property1

Can anyone shed some light on this? I thought it should work..

Thanks


IBaseSub<T> requires IBase. I say "requires" because it more accurately reflects the practical implications than to say it "inherits" IBase, which implies overriding and other things that simply don't happen with interfaces. A class which implements IBaseSub<T> can actually be said to implement both, like so:

public class MyClass : IBase, IBaseSub<YourObject>

Going back to what I said about inheritance - there is no such thing with interfaces, which means just because both interfaces have a property with the same name, the derived one isn't overriding or hiding the base one. It means that your class must now literally implement two properties with the same name to fulfill both contracts. You can do this with explicit implementation:

public class MyClass : IBase, IBaseSub<YourObject>
{
    public YourObject Property1 { get; set; }
    MyObject IBase.Property1 { get; set; }
}


You need to implement the properties from both IBase and IBaseSub<YourObject>, since the latter expands on the former.

Using new in IBaseSub<T> does not let you "off the hook" regarding the necessity to have a MyObject Property1 { get; set; }. It simply allows you to declare another property named Property1 that implementors of IBaseSub<T> must have.

Since you cannot have two properties with the same name in MyClass, you will be forced to implement at least one of them explicitly:

public class MyClass : IBaseSub<YourObject>
{
    MyObject IBase.Property1 { get; set; }
    public YourObject Property1 { get; set; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消