【发布时间】:2016-08-23 22:23:11
【问题描述】:
static IEnumerable<U> DoSomething<T, U>(IEnumerable<T> a)
where T : U
{
// Works, compiler can compile-time statically cast
// T as U.
T testA = default(T);
U testB = testA;
// And the following works, though:
IEnumerable<string> test2A = null;
IEnumerable<object> test2B = test2A;
// Doesn’t work. Compiler cannot compile-time statically
// cast IEnumerable<T> to IEnumerable<U> even though it is
// out and T is U.
return a;
}
我有代码,能够执行这种类型的隐式转换将节省我编写大量样板接口实现代码。
这似乎是协方差应该提供帮助的那种事情。
但我总是在上面的return a; 行收到此错误:
错误 CS0266:无法将类型“System.Collections.Generic.IEnumerable
”隐式转换为“System.Collections.Generic.IEnumerable”。存在显式转换(您是否缺少演员表?)
为什么会这样?有没有办法在不执行return from o in a select o; 之类的操作的情况下解决这个问题?
【问题讨论】: