我有一个泛型类,我正试图为其实现隐式类型转换。虽然它基本上是有效的,但它不适用于界面转换。经过进一步调查,我发现存在一个编译器错误:“用户定义的接口转换”适用。虽然我知道这在某些情况下应该强制执行,但我所做的似乎是合法的。
下面是一个例子:
public class Foo<T> where T : IBar
{
private readonly T instance;
public Foo(T instance)
{
this.instance = instance;
}
public T Instance
{
get { return instance; }
}
public static implicit operator Foo<T>(T instance)
{
return new Foo<T>(instance);
}
}
使用它的代码:
var concreteReferenceToBar = new ConcreteBar();
IBar intefaceReferenceToBar = concreteReferenceToBar;
Foo<ConcreteBar> concreteFooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromInterfaceBar = intefaceReferenceToBar; // doesn't work
有人知道变通方法吗,或者有人能满意地解释为什么我不能施展才华
interfaceReferenceToBar
含蓄地
Foo<IBar>
编辑: