这是我正在使用的简化版本,只是为了让您知道我正在努力完成的事情:
public Dictionary<int, Func<int>> Magic(Dictionary<int, int> dictionary)
{
return dictionary
.Select(v => new
{
key = v.Key,
function = new Func<int>(() => v.Value + 5) // *
})
.ToDictionary(v => v.key, v => v.function);
}
是否可以缩短标有 (*) 的行?因为当我尝试删除冗余(在我看来)委托(delegate)创建时,它给出了错误:
function = () => v.Value + 5 // *
但是应该不会报错,返回的类型是什么一目了然...
最佳答案
Lambda 表达式是无类型的。这就是为什么您必须向编译器添加一些信息来确定它的类型(通过为它们提供一些上下文)。
Note that lambda expressions in themselves do not have a type because the common type system has no intrinsic concept of "lambda expression." However, it is sometimes convenient to speak informally of the "type" of a lambda expression. In these cases the type refers to the delegate type or Expression type to which the lambda expression is converted.
您可以通过分配给它的变量/参数/属性/字段的类型来完成:
Func<int> func = () => 5;
或者将其转换为委托(delegate):
var func = (Func<int>)(() => 5);
这是必要的,因为您可以想象将自己的委托(delegate)声明为
public delegate int MyDelegate();
编译器如何知道您的匿名类型属性是否应键入为 MyDelegate
或 Func<int>
?
关于C# LINQ 和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29057028/