简体   繁体   English

根据函数的表达式参数推断第二个通用参数

[英]Infer second generic parameter based on the expression argument of the function

This question is an extension of Partial type inference If partial type inference is not possible, could anyone please explain how OrderByDescending extension method is working? 这个问题是对部分类型推断的扩展如果无法进行部分类型推断,那么谁能解释一下OrderByDescending扩展方法的工作方式吗? Please note that when I call OrderByDescending(m=>m.DateProp), I am not asked to provide Type parameter. 请注意,当我调用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? 谁能解释一下OrderByDescending扩展方法如何工作?

I surely can. 我当然可以。

static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>
(
  this IQueryable<TSource> source, 
  Expression<Func<TSource, TKey>> keySelector);

When you call foo.OrderByDescending( x => bar ) type inference proceeds as follows. 当您调用foo.OrderByDescending( x => bar )类型推断如下进行。

  • First a set of bounds for TSource is inferred by examining foo . 首先,通过检查foo来推断TSource一组边界。
  • Then we ask "are there any more inferences we can make without knowing TSource?" 然后我们问“在不知道TSource的情况下还能做出更多推断吗?” The answer is no, so we fix the value of TSource to the best member of the bound set. 答案是否定的,因此我们将TSource的值固定为绑定集的最佳成员。 Call it S . 称之为S
  • Then we ask "given the value of TSource is S , can we infer the value of TKey ? Yes. We apply the type value S to x , and then infer the type of expression bar in an environment where x is of type S . 然后我们问“给定TSource值为S ,可以推断TKey的值吗?是。我们将类型值S应用于x ,然后在x的类型为S的环境中推断表达式bar的类型。
  • The type of bar gives us the type for TKey and we're done. bar的类型为我们提供了TKey的类型,我们就完成了。

If partial type inference is not possible,... 如果无法进行部分类型推断,则...

Partial type inference is not impossible . 部分类型推断并非不可能 Rather, it's not implemented . 相反,它没有实现 It's possible to add the feature to C#; 可以将功能添加到C#中。 no one has done it. 没有人做到这一点。

Regardless, whether or not inference from a partial set of bounds is implemented or possible, there's no difficulty in doing a complete inference of all the types in a call to OrderByDescending . 无论是否实现了从局部范围的推理,或者在可能的情况下,在对OrderByDescending的调用中对所有类型进行完整的推理都没有困难。 Obviously we designed the algorithm specifically to be able to handle OrderByDescending , Join and so on. 显然,我们专门设计了算法来处理OrderByDescendingJoin等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM