简体   繁体   中英

C# interface property implementation

interface IAlpha
{
    IBeta BetaProperty { get; set; }
}

interface IBeta
{

}

class Alpha : IAlpha
{
    public Beta BetaProperty { get; set; } // error here
}

class Beta : IBeta
{

}

'InterfaceTest.Alpha' does not implement interface member 'InterfaceTest.IAlpha.BetaProperty'. 'InterfaceTest.Alpha.BetaProperty' cannot implement 'InterfaceTest.IAlpha.BetaProperty' because it does not have the matching return type of 'InterfaceTest.IBeta'.

My question is why is a property implementation restricted to the very same type. Why can't I use the derived type instead?

You have to implement the exact same interface. For example, this should be valid:

 IAlpha alpha = new Alpha();
 alpha.BetaProperty = new SomeOtherIBetaImplementation();

... but that wouldn't work with your code which always expects it to be a Beta , would it?

You can use generics for this though:

interface IAlpha<TBeta> where TBeta : IBeta
{
    TBeta BetaProperty { get; set; }
}

...

public class Alpha : IAlpha<Beta>

Of course, that may be overkill - you may be better just using a property of type IBeta in Alpha , exactly as per the interface. It depends on the context.

An interface declares a set of methods the class will have, so anyone using that interface knows what to expect.

So, if you're implementing that interface, you must implement the exact interface, so all the other users get what they expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM