implicit operator using interfaces
我有一个泛型类,我正试图实现隐式类型转换。虽然它主要是工作的,但它不适用于接口转换。经过进一步的调查,我发现有一个编译器错误:"用户定义的接口转换"适用。虽然我知道这在某些情况下应该强制执行,但我所做的似乎是合法的。
下面是一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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); } } |
使用代码:
1 2 3 4 5 | var concreteReferenceToBar = new ConcreteBar(); IBar intefaceReferenceToBar = concreteReferenceToBar; Foo<ConcreteBar> concreteFooFromConcreteBar = concreteReferenceToBar; Foo<IBar> fooFromConcreteBar = concreteReferenceToBar; Foo<IBar> fooFromInterfaceBar = intefaceReferenceToBar; // doesn't work |
是否有人知道解决方法,或者有人能以令人满意的方式解释为什么我不能将
编辑:看来协方差可以拯救我们。希望C 4.0规范允许使用协方差隐式转换接口类型。
您不能这样做的原因是C语言规范中特别禁止这样做:
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.
来源