对不起,标题很笨拙,但 SO 不会让我把它留在“隐式转换没有按预期工作”。
考虑这个简单的泛型类型:
public class Foo<T> {
public T Bar;
public Foo(T bar) => Bar = bar;
public static implicit operator Foo<T>(T bar) => new(bar);
}
注意隐式转换(至少在我看来)应该允许我直接从任何 Foo<T>
创建一个 T
,如下所示:
int[] xs = new[] { 1, 2, 3 };
IEnumerable<int> ys = xs.AsEnumerable();
Foo<IEnumerable<int>> foo = ys; // CS0266
但是上面会产生一个编译器错误:
<块引用>CS0266:无法将类型“System.Collections.Generic.IEnumerable
有趣的是,下面的代码运行没有问题:
int[] xs = new[] { 1, 2, 3 };
Foo<IEnumerable<int>> foo = xs; // no error
并且使用显式强制转换“修复”了编译器错误,但在运行时崩溃:
int[] xs = new[] { 1, 2, 3 };
IEnumerable<int> ys = xs.AsEnumerable();
Foo<IEnumerable<int>> foo = (Foo<IEnumerable<int>>)ys; // InvalidCastException
<块引用>
InvalidCastException:无法将“System.Int32[]”类型的对象转换为“Foo`1[System.Collections.Generic.IEnumerable`1[System.Int32]]”。
这里发生了什么?我完全被难住了,一点线索也没有。
.NET 小提琴:https://dotnetfiddle.net/wNHUtl