字典中的Func,此代码如何工作? 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> Operation(String input) => (x,y) =>
            (
                (input.Equals("+") ? x + y :
                    (input.Equals("*") ? x * y : int.MinValue)
                )
            );
        _operators.Push(Operation(op)(num1,num2));

解决方法

此(以及其他带有=>的表达式)

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

lambda expression

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

当我们编写以下内容时:

_operationFunction[op](num1,num2)

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

因此,如果op的值是字符串"+",则_operationFunction[op]返回一个对委托的引用,该引用实质上由lambda表达式描述:

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

然后将此引用指向的“函数”应用于参数num1num2

您可以在Func<T1,T2,TResult>上阅读更多有关代码中使用的代码的信息。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...