开发者

Implementing generic interfaces

开发者 https://www.devze.com 2023-02-12 22:54 出处:网络
I have written this code. public interface IMusicInstrument { string InstrumentType(int InstrumentId); } public interface IGuitar<T, K> where T : GuitarBase where K : IMusicInstrument

I have written this code.

public interface IMusicInstrument
{
  string InstrumentType(int InstrumentId);                
}

public interface IGuitar<T, K> where T : GuitarBase where K : IMusicInstrument
{
    string Name { get; set; }
    string GetType(T t);
}

p开发者_开发问答ublic class ElectricGuitar : GuitarBaseExtended, IGuitar<ElectricGuitar, IMusicInstrument>
{
    public string Name { get; set; }
    public string GetType(ElectricGuitar t)
    {
        return "The electric guitar is: " + t.Name;
    }
}

I was thinking that because the IMusicInstrument requires that I implement a method called InstrumentType that when I include it as a parameter in my IGuitar interface which is implemented on hte ElectricGuitar class that I would get a compile time error. However, I do not.

Am I implementing it wrong?

My goal is to implement the IMusicInstrument into the generic typed IGuitar interface so that both the requirements from IMusiInstrument and IGuitar are enforced.

Any ideas?


You haven't said that ElectricGuitar implements IMusicInstrument... you've just said that it implements IGuitar<ElectricGuitar, IMusicInstrument>, and that doesn't have the InstrumentType method. It's not clear why you've got the K type parameter in IGuitar<T, K> at all, given that it's not used within the interface.

0

精彩评论

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

关注公众号