C# LINQ 和函数

C# LINQ and func

这是我正在使用的简化版本,只是为了让您知道我正在努力完成的事情:

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);
}

有没有办法把标有(*)的那一行缩短一点?因为当我尝试删除冗余(在我看来)委托创建时,它给出了错误:

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.

from Lambda Expressions (C# Programming Guide)

您可以通过将其分配给 variable/parameter/property/field 的类型来完成:

Func<int> func = () => 5;

或将其转换为委托:

var func = (Func<int>)(() => 5);

这是必要的,因为您可以想象将自己的委托声明为

public delegate int MyDelegate();

编译器如何知道您的匿名类型 属性 应该键入 MyDelegate 还是 Func<int>

你可以将整个事情缩短为:

public Dictionary<int, Func<int>> Magic(Dictionary<int, int> dictionary)
{
    return dictionary
        .ToDictionary(v => v.Key, v => (Func<int>)(() => v.Value + 5));
}

但您仍然需要显式转换为 Func<int>

唯一的其他方法是:

public Dictionary<int, Func<int>> Magic(Dictionary<int, int> dictionary)
{
    return dictionary
        .ToDictionary<KeyValuePair<int, int>, int, Func<int>>(
            v => v.Key, 
            v => () => v.Value + 5);
}