【问题标题】:Linq .Select() / .SelectMany() automatically uses second, optional parameterLinq .Select() / .SelectMany() 自动使用第二个可选参数
【发布时间】:2016-09-22 12:13:06
【问题描述】:

我刚刚在 Linq 中发现了最奇怪的行为:

当调用一元函数时,我喜欢只传递函数名,而不是

var foo = myList.Select(item => MyFunc(item));

我写

var foo = myList.Select(MyFunc);

应该是一样的。只有在某些情况下,它不是!也就是说,如果函数有第二个参数是 int 并且是可选的:

private string MyFunc(string input, int foo = 0)
{
   ...
}

在这种情况下,声明

var foo = myList.Select(MyFunc);

等于

var foo = myList.Select((item, index) => MyFunc(item, index));

如果第二个参数不是可选的或者不是int,编译器会报错,但在这种情况下,它只是偷偷摸摸地让你吃惊。

有没有其他人遇到过这种情况?还有哪些其他 Linq 表达式以这种方式工作? (到目前为止,.SelectMany() 确实如此)。解决这种行为的最优雅的方法是什么(并防止其他人落入同样的陷阱?)

【问题讨论】:

    标签: c# linq select optional-parameters


    【解决方案1】:

    这实际上不是特定 LINQ 扩展方法的问题,而是如何处理 Funcs 和 Actions 的可选参数,简而言之 - 它们不是,它们被视为常规参数,默认值被省略选择对应的Func/Action签名时。看看这里Optional Parameters, No overload for 'Employee' matches delegate 'System.Func<Employee> 或这里Invoke Func<T1, T2, T3> which has optional parameters?

    换句话说,您的MyFunc 不能用作Func&lt;string, string&gt;,您必须使用Func&lt;string, int, string&gt;,如果Select 恰好作为添加索引的重载存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多