简体   繁体   English

C#3.0 Func / OrderBy类型推断

[英]C# 3.0 Func/OrderBy type inference

So odd situation that I ran into today with OrderBy: 我今天和OrderBy碰到了奇怪的情况:

Func<SomeClass, int> orderByNumber = 
  currentClass => 
   currentClass.SomeNumber;

Then: 然后:

someCollection.OrderBy(orderByNumber);

This is fine, but I was going to create a method instead because it might be usable somewhere else other than an orderBy. 这很好,但我打算创建一个方法,因为它可能在除orderBy之外的其他地方可用。

private int ReturnNumber(SomeClass currentClass)
{
  return currentClass.SomeNumber;
}

Now when I try to plug that into the OrderBy: 现在,当我尝试将其插入OrderBy时:

someCollection.OrderBy(ReturnNumber);

It can't infer the type like it can if I use a Func. 如果我使用Func,它无法推断它的类型。 Seems like to me they should be the same since the method itself is "strongly typed" like the Func. 在我看来它们应该是相同的,因为方法本身就像Func一样是“强类型”的。

Side Note: I realize I can do this: 旁注:我意识到我可以这样做:

Func<SomeClass, int> orderByNumber = ReturnNumber;

This could also be related to "return-type type inference" not working on Method Groups . 这也可能与“返回类型推断”无关,而不适用于方法组

Essentially, in cases (like Where 's predicate) where the generic parameters are only in input positions, method group conversion works fine. 本质上,在通用参数仅在输入位置的情况下(如Where的谓词),方法组转换工作正常。 But in cases where the generic parameter is a return type (like Select or OrderBy projections), the compiler won't infer the appropriate delegate conversion. 但是在泛型参数是返回类型(如SelectOrderBy投影)的情况下,编译器不会推断出适当的委托转换。

ReturnNumber is not a method - instead, it represents a method group containing all methods with the name ReturnNumber but with potentially different arity-and-type signatures. ReturnNumber 不是一个方法 - 相反,它表示一个方法组,其中包含名为ReturnNumber但具有可能不同的arity-and-type签名的所有方法。 There are some technical issues with figuring out which method in that method group you actually want in a very generic and works-every-time way. 有一些技术问题可以通过非常通用和每次工作的方式确定您实际想要的方法组中的哪种方法。 Obviously, the compiler could figure it out some, even most, of the time, but a decision was made that putting an algorithm into the compiler which would work only half the time was a bad idea. 显然,编译器可以在某些时候,甚至是大多数时候都能找到它,但是决定将算法放入编译器只能工作一半的时间是一个坏主意。

The following works, however: 但是,以下工作:

someCollection.OrderBy(new Func<SomeClass, int>(ReturnNumber))

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

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