我有一个通用类,我正在尝试为其实现隐式类型转换。虽然大多数情况下都可以使用,但不适用于界面投射。经过进一步调查,我发现有一个编译器错误:“适用于用户定义的接口转换”。虽然我知道应该在某些情况下强制执行,但是我想做的事情似乎是合理的情况。
这是一个例子:
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规范允许使用协方差隐式转换接口类型。
胡说叔叔
慕无忌1623718
相关分类