为什么可以在“OK”行进行转换,而在“NOT OK”行则不行?
var queryable = new int[]{1, 2, 3}.AsQueryable();
var x = (Expression<Func<IQueryable<int>>>)(() => (from c in queryable select c));
var yy = (Expression<Func<IEnumerable<int>>>)x; // NOT OK (does not compile)
var zz = (Expression<Func<IEnumerable<int>>>)(() => (from c in queryable select c)); // OK
更新:错误信息是:
Cannot convert type
System.Linq.Expressions.Expression<System.Func<System.Linq.IQueryable<int>>>
to 'System.Linq.Expressions.Expression<System.Func<System.Collections.Generic.IEnumerable<int>>
>'
最佳答案
因为 Expression
是一个类并且IEnumerable
是一个接口(interface)。类不是协变的,而接口(interface)和委托(delegate)是协变的。
这意味着您无法转换 Expression<A>
至 Expression<B>
即使 B 是 A 的基类。
所以如果这一行:
() => (from c in queryable select c)
返回
Func<IQueryable<int>>
它可以转换成
Func<IEnumerable<int>>
但如果你已经拥有
Expression<Func<IQueryable<int>>>
它不能转换成
Expression<Func<IEnumerable<int>>>
关于c# - IQueryable 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21629603/