为什么这种转换不起作用?
public interface IMyInterface
{
}
public interface IMyInterface2 : IMyInterface
{
}
public class MyContainer<T> where T : IMyInterface
{
public T MyImpl {get; private set;}
public MyContainer()
{
MyImpl = Create<T>();
}
public static implicit T (MyContainer<T> myContainer)
{
return myContainer.MyImpl;
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用我的类时,它会导致编译时错误:
IMyInterface2 myImpl = new MyContainer<IMyInterface2>();
Run Code Online (Sandbox Code Playgroud)
无法从MyContainer <IMyInterface2> 转换为IMyInterface2 ...嗯
您无法定义到接口的隐式转换.因此,通用隐式操作对接口无效.见blackwasp.co.uk
您可能无法创建将类转换为已定义接口的运算符.如果需要转换为接口,则该类必须实现该接口.
您可能只需编写以下内容,而无需隐式魔术:
IMyInterface2 myImpl = new MyContainer<IMyInterface2>().MyImpl;
Run Code Online (Sandbox Code Playgroud)