简体   繁体   中英

Expose child interface methods in c#

We have a Manager class which exposes a property of type IDevice,

public interface IDevice {
    string GetId();
}

public class Manager{

    public IDevice Device
    {
     get;
    }

}

Now I have a new interface which extends from IDevice,

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

Is there a way by which can we expose the methods of IBleDevice to consumer of the class with the same parent reference (IDevice) without casting??

Eg:

void main(){
  new Manager().Device.GetBleId(); // which requires casting now
}

How about use Generic method.

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

You can use like this.

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

As you said if the consumer is not aware of IBleDevice , You can use "dynamic" type in your manager class for Device property. Like this:

public dynamic Device
    {
     get;
    }

Then the consumer can write

 new Manager().Device.GetBleId();

And you will not get any compile error and also in runtime GetBleId will execute

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