使用接口的隐式运算符

使用接口的隐式运算符

问题描述:

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

I have a generic class that I'm trying to implement implicit type casting for. While it mostly works, it won't work for interface casting. Upon further investigation, I found that there is a compiler error: "User-defined conversion from interface" that applies. While I understand that this should be enforced in some cases, what I'm trying to do does seem like a legitimate case.

这是一个例子:

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,因为在我的情况是它没有被转换,而是只包含在 Foo 中?

Does anyone know a workaround, or can anyone explain in a satisfactory way why I shuouldn't be able to cast interfaceReferenceToBar implicitly to Foo<IBar>, since in my case it is not being converted, but only contained within Foo?

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

It looks like covariance might offer salvation. Let's hope the C# 4.0 specification allows for implicit casting of interface types using covariance.

之所以不能这样做,是因为在C#语言规范中是明确禁止的:

The reason you can't do this is because it is specifically forbidden in the C# language specification:

来源:ECMA-334 第 15.10.4 节一个>

允许类或结构声明来自源的转换类型 S 到目标类型 T 提供所有以下说法正确的是:

A class or struct is permitted to declare a conversion from a source type S to a target type T provided all of the following are true:

  • ...
  • S 和 T 都不是 object接口类型.

用户定义的转换不是允许从或转换为接口类型.特别是,这限制确保没有发生用户定义的转换当转换为接口类型时,并且转换为interface-type 仅当实际转换的对象执行指定的接口类型.

User-defined conversions are not allowed to convert from or to interface-types. In particular, this restriction ensures that no user-defined transformations occur when converting to an interface-type, and that a conversion to an interface-type succeeds only if the object being converted actually implements the specified interface-type.