相关疑难解决方法(0)

隐式运算符使用接口

我有一个泛型类,我正在尝试实现隐式类型转换.虽然它主要起作用,但它不适用于界面转换.经过进一步调查,我发现存在编译器错误:"来自接口的用户定义转换"适用.虽然我知道在某些情况下应该强制执行,但我正在尝试做的事情似乎是合法的案例.

这是一个例子:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用它的代码:

var concreteReferenceToBar = new ConcreteBar();
IBar intefaceReferenceToBar = concreteReferenceToBar;
Foo<ConcreteBar> concreteFooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromInterfaceBar = intefaceReferenceToBar; // doesn't work
Run Code Online (Sandbox Code Playgroud)

有没有人知道一个解决方法,或者任何人都能以令人满意的方式解释为什么我不能施展 interfaceReferenceToBar隐式地Foo<IBar>,因为在我的情况下它没有被转换,只包含在Foo中?

编辑: 看起来协方差可能提供救赎.我们希望C#4.0规范允许使用协方差隐式转换接口类型.

c# compiler-construction generics casting implicit-conversion

53
推荐指数
1
解决办法
2万
查看次数