我有界面
public interface ICallFlowApplication
{
void HandleCall();
}
实施
public class TestCallFlowApplication : ICallFlowApplication
{
public void HandleCall()
{
// blah blah
现在由于某种原因,我需要将一个对象传递给该方法,以便
public void HandleCall(SipChannel channel)
{
我认为我必须将接口ICallFlowApplication
重构为
public interface ICallFlowApplication
{
void HandleCall(SipChannel channel);
}
但是SipChannel是一个特殊频道。有不同的渠道。我想在这里使用依赖注入。 我的问题:
ICallFlowApplication
?IChannel
?答案 0 :(得分:2)
使用泛型 -
public interface ICallFlowApplication<T> where T : IChannel
{
void HandleCall(T channel);
}
public class TestCallFlowApplication : ICallFlowApplication<SipChannel>
{
public void HandleCall(SipChannel channel){}
}
public class SipChannel : IChannel {}
public interface IChannel {}
以下是将SipChannel包装在您自己的对象中并从IChannel继承的示例 -
public interface ICallFlowApplication<T> where T : IChannel
{
void HandleCall(T channel);
}
public class TestCallFlowApplication : ICallFlowApplication<MySipChannel>
{
public void HandleCall(MySipChannel channel){}
}
public class MySipChannel : IChannel
{
private SipChannel _channel;
public MySipChannel(SipChannel channel)
{
_channel = channel;
}
// expose methods/properties you need
}
public interface IChannel {}
public class SipChannel {} // declared in some unknown dll
答案 1 :(得分:1)
这是一种方法,可能或可能不适合您的需要。
正如Tom A.所说,最好的办法是创建一个IChannel
界面,并将其包裹在第三方提供的频道周围。如果您必须对这些通道执行某些操作,则可以在界面中指定它,并根据每个供应商的具体情况为每个通道单独实施。
public interface IChannel
{
void DoSomething();
string DoSomethingElse();
}
public class SipChannel : IChannel
{
public void DoSomething()
{
//go do some stuff
}
public string DoSomethingElse()
{
return "I did some stuff for you.";
}
}
public OtherChannel : IChannel
{
public void DoSomething()
{
//go do some stuff
}
public string DoSomethingElse()
{
return "I'm not sure what this one does yet.";
}
}
现在,HandleCall
可以拥有签名:void HandleCall(IChannel channel);
并实现如下:
public void HandleCall(IChannel channel)
{
channel.DoSomething();
channel.DoSomethingElse();
}
这将调用您传入的特定实例的实现。