C# LINQ 和函数

标签 c# linq lambda 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);
}

是否可以缩短标有 (*) 的行?因为当我尝试删除冗余(在我看来)委托(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.

from Lambda Expressions (C# Programming Guide)

您可以通过分配给它的变量/参数/属性/字段的类型来完成:

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

或者将其转换为委托(delegate):

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

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

public delegate int MyDelegate();

编译器如何知道您的匿名类型属性是否应键入为 MyDelegateFunc<int>

关于C# LINQ 和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29057028/

相关文章:

c# - 以编程方式解锁 Windows

c# - 字幕仅适用于全屏

c# - Specflow Hook ,如何获得不确定或待定结果?

C# 排序字母数字列表

C++ 如何获得指向 lambda 函数的空指针?

c# - WriteableBitmap访问冲突问题

c# - 使用 Linq 查询丢失 foreach

linq - 将许多引用组合成 linq 查询

c++ - 如何为 ostream 创建 lambda?

java - 函数式接口(interface)继承怪癖