无法推断Lambda表达式类型参数

m1n*_*keh 1 c# lambda

可能有人帮助我了解在下面的例子中实际上是怎么回事,这样我可以在未来的自己..因为明白为什么错误获取或如何解决它,而不只是重新写...

给出这种方法方法:

public static void DoNothing(string v)
{
    // do nothing
}
Run Code Online (Sandbox Code Playgroud)

试图像这样执行它会产生错误" 无法推断出方法的类型参数..请尝试明确指定类型参数. ":

myList.Select(x => DoNothing(x)); // does not work
var r = myList.Select(x => DoNothing(x)); // just a ?
Run Code Online (Sandbox Code Playgroud)

但是,只要它返回一些东西,即:

private static string ReturnString(string v)
{
    return v;
}
Run Code Online (Sandbox Code Playgroud)

这很好用:

myList.Select(x => ReturnString(x)); // works
var r = myList.Select(x => ReturnString(x)); // IEnumerable<string>
Run Code Online (Sandbox Code Playgroud)

所以我想这与void返回类型有关?

我可以永远不会工作,因为没有任何东西返回,或者是否有一些我缺少/无法弄清楚的神奇语法(!)

唯一的方法我似乎可以得到这个功能如下:

foreach (var item in myList)
{
    DoNothing(item);    // works fine.
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Chr*_*air 5

Select方法期望其中的lambda表达式返回值.因为DoNothing(v)是一种void方法,它根本不返回任何东西.

错误消息来自通用推理,它将尝试Select根据其中表达式的结果调用通过调用生成的变量类型.但由于没有返回类型(void不计数),它抱怨.

想象一下,如果你链接另一个SelectWhere打电话:

myList.Select(x => DoNothing(x)).Where(v => ????); //what is "v" here? void? That doesn't work

var value = myList.Select(x => DoNothing(x)).First(); //what is "value" here? void?
Run Code Online (Sandbox Code Playgroud)

所以你可以看到它是如何无法解决的.

一旦你更新它以进行调用ReturnString,那么推理会选择string返回类型,一切都很好.

myList.Select(x => ReturnString(x)).Where(v => v == "Hello World!"); // "v" is a string here, everything is fine.

string value = myList.Select(x => ReturnString(x)).First(); //what is "value" here? It's a "string" type as specified by "ReturnString"
Run Code Online (Sandbox Code Playgroud)

  • @ m1nkeh不使用`.Select(...)`的`void`方法,它绝对没有意义.`.Select(...)`应该用于将序列的元素"转换"成其他东西,例如将`List <string>`转换为`List <int>` (3认同)
  • 如果您的意图是"选择"意思,"对于`myList`中的每个元素,请调用此方法 - 我不关心返回值",然后是_typically_,这就是`foreach`将用于什么.LINQ通常用于_querying_数据,理想情况下没有副作用.也就是说,您可以随时滚动自己的扩展方法(如[`List <T> .ForEach`](https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,0e5a9cf0a310b9e5,references ))方法,虽然它不经常以这种方式完成,但是如果它适合你,那么你就更有力量了. (2认同)