可能有人帮助我了解在下面的例子中实际上是怎么回事,这样我可以鱼在未来的自己..因为明白为什么错误获取或如何解决它,而不只是重新写...
给出这种方法方法:
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)
提前致谢!
该Select
方法期望其中的lambda表达式返回值.因为DoNothing(v)
是一种void
方法,它根本不返回任何东西.
错误消息来自通用推理,它将尝试Select
根据其中表达式的结果调用通过调用生成的变量类型.但由于没有返回类型(void
不计数),它抱怨.
想象一下,如果你链接另一个Select
或Where
打电话:
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)