这个问题是 Partial type inference 如果无法进行部分类型推断,谁能解释一下 OrderByDescending 扩展方法是如何工作的?请注意,当我调用 OrderByDescending(m=>m.DateProp) 时,不会要求我提供 Type 参数。
static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(
this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector);
最佳答案
could anyone please explain how OrderByDescending extension method is working?
我当然可以。
static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>
(
this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector);
当您调用 foo.OrderByDescending( x => bar )
时类型推断如下。
- 首先是
TSource
的一组界限通过检查foo
推断出. - 然后我们问“在不知道 TSource 的情况下我们还能做出更多推论吗?”答案是否定的,所以我们固定
TSource
的值。到绑定(bind)集的最佳成员。调用S
. - 然后我们问“给定
TSource
的值是S
,我们可以推断出TKey
的值吗?是的。我们将类型值S
应用到x
,然后推断出表达式bar
在x
的类型为S
的环境中。 bar
的类型给我们TKey
的类型我们完成了。
If partial type inference is not possible,...
部分类型推断并非不可能。相反,它没有实现。可以将该功能添加到 C#;没有人做过。
无论是否实现或可能从部分边界集推断,在调用 OrderByDescending
时对所有类型进行完整推断都没有困难。 .显然,我们专门设计了能够处理 OrderByDescending
的算法。 , Join
等等。
关于c# - 根据函数的表达式参数推断第二个泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40337300/