实现通用接口

时间:2011-02-24 11:04:22

标签: generics interface

我已经写了这段代码。

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);
}

public class ElectricGuitar : GuitarBaseExtended, IGuitar<ElectricGuitar, IMusicInstrument>
{
    public string Name { get; set; }
    public string GetType(ElectricGuitar t)
    {
        return "The electric guitar is: " + t.Name;
    }
}

我在想,因为IMusicInstrument要求我实现一个名为InstrumentType的方法,当我将它作为参数包含在我的IGIitar接口中时,它在hte ElectricGuitar类上实现,我会得到一个编译时错误。但是,我没有。

我执行错了吗?

我的目标是将IMusicInstrument实现到通用类型的IGuitar接口中,以便强制执行IMusiInstrument和IGuitar的要求。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你没有说过ElectricGuitar实现了IMusicInstrument ...你刚才说它实现了IGuitar<ElectricGuitar, IMusicInstrument>,而 没有InstrumentType方法。目前尚不清楚为什么你在K中有IGuitar<T, K>类型参数,因为它没有在界面中使用。