我有一个通用类,我正在尝试实现隐式类型转换。虽然它大部分都可以工作,但对于接口转换却不起作用。进一步调查后,我发现存在编译器错误:“从接口的用户定义的转换”适用。虽然我理解在某些情况下应该强制执行这一点,但我所尝试的似乎是一个合法的案例。
以下是一个示例:
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>
,因为在我的情况下它并没有被转换,而只是包含在Foo中呢?
编辑: 看起来协变可能会提供救赎。希望C# 4.0规范允许使用协变隐式转换接口类型。