首页 > 解决方案 > 字典中的函数,这段代码是如何工作的?C#

问题描述

我是 C# 的新手,我的教授给了我这段代码,你能解释一下它是如何工作的吗?我对所有这些“=>”运算符以及 Dictionary 中发生的事情感到好奇。

            _operationFunction = new Dictionary<string, Func<int, int, int>>
            {
                ["+"] = (fst, snd) => (fst + snd),
                ["-"] = (fst, snd) => (fst - snd),
                ["*"] = (fst, snd) => (fst * snd),
                ["/"] = (fst, snd) => (fst / snd)
            };
           _operators.Push(_operationFunction[op](num1, num2));

        Func<int, int, int> Operation(String input) => (x, y) =>
            (
                (input.Equals("+") ? x + y :
                    (input.Equals("*") ? x * y : int.MinValue)
                )
            );
        _operators.Push(Operation(op)(num1, num2));

标签: c#visual-studiodelegatesexplain

解决方案


这(以及其他表达式,with =>

(fst, snd) => (fst + snd)

是一个lambda 表达式

字典中的 lambda 表达式表示整数之间的算术运算。因此,对于加法 (+)、乘法 (*)、减法 (-) 和除法 (/) 这四种操作中的每一种,都提供了一个 lambda 表达式来描述这些操作。

当我们编写以下内容时:

_operationFunction[op](num1, num2)

获取与键关联的字典的值,op然后将返回的函数(值)应用于整数num1num2

因此,如果 的值为opstring "+",则_operationFunction[op]返回对委托的引用,本质上由 lambda 表达式描述:

(fst, snd) => (fst + snd)

然后这个引用指向的“函数”被应用于参数num1num2

您可以在Func<T1,T2,TResult>阅读更多重新分级代码中使用的内容。


推荐阅读