使用接口的隐式运算符

时间:2020-03-06 14:49:23  来源:igfitidea点击:

我有一个通用类,我正在尝试为其实现隐式类型转换。虽然大多数情况下都可以使用,但不适用于界面投射。经过进一步调查,我发现存在一个编译器错误:"适用于用户定义的接口转换"。虽然我知道在某些情况下应该强制执行,但是我想做的事情似乎是合理的情况。

这是一个例子:

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中?

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

解决方案

我们无法执行此操作的原因是,它在Clanguage规范中被明确禁止:

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:
  
  
  ...
  Neither S nor T is object or an 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.

来源