在C#中公开子接口方法

我们有一个Manager类,它公开了IDevice类型的属性,


public interface IDevice {

    string GetId();

}


public class Manager{


    public IDevice Device

    {

     get;

    }


}

现在,我有了一个从IDevice扩展的新接口,


public interface IBleDevice : IDevice{

   string GetBleId();

}

有没有一种方法可以将IBleDevice的方法公开给具有相同父引用(IDevice)的类的使用者而无需强制转换?


例如:


void main(){

  new Manager().Device.GetBleId(); // which requires casting now

}


跃然一笑
浏览 149回答 2
2回答

一只萌萌小番薯

如何使用通用方法。public interface IDevice{&nbsp; &nbsp; string GetId();}public class Manager{&nbsp; &nbsp; public TResult GetDevice<TResult>()&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; where TResult : IDevice&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return (TResult)Device;&nbsp; &nbsp; }&nbsp; &nbsp; public IDevice Device&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get;&nbsp; &nbsp; }}public interface IBleDevice : IDevice{&nbsp; &nbsp; string GetBleId();}您可以这样使用。new Manager().GetDevice<IBleDevice>().GetBleId(); // which requires casting now

富国沪深

如您所说,如果使用者不了解IBleDevice,则可以在管理器类中为设备属性使用“动态”类型。像这样:public dynamic Device&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp;get;&nbsp; &nbsp; }然后消费者可以写&nbsp;new Manager().Device.GetBleId();而且您将不会获得任何编译错误,并且在运行时GetBleId也将执行
打开App,查看更多内容
随时随地看视频慕课网APP