簡體   English   中英

在C#中公開子接口方法

[英]Expose child interface methods in 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
}

如何使用通用方法。

public interface IDevice
{
    string GetId();
}

public class Manager
{

    public TResult GetDevice<TResult>() 
        where TResult : IDevice
    {
        return (TResult)Device;
    }

    public IDevice Device
    {
        get;
    }
}

public interface IBleDevice : IDevice
{
    string GetBleId();
}

您可以這樣使用。

new Manager().GetDevice<IBleDevice>().GetBleId(); // which requires casting now

如您所說,如果使用者不了解IBleDevice ,則可以在管理器類中為Device屬性使用“動態”類型。 像這樣:

public dynamic Device
    {
     get;
    }

然后消費者可以寫

 new Manager().Device.GetBleId();

而且您將不會獲得任何編譯錯誤,並且在運行時還將執行GetBleId

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM