问题描述
我是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表达式表示整数之间的算术运算。因此,对于加法(+),乘法(*),减法(-)和除法(/)四个操作中的每一个,都会提供一个lambda表达式来描述这些操作。
当我们编写以下内容时:
_operationFunction[op](num1,num2)
获取与键op
关联的字典的值,然后将返回的函数(值)应用于整数num1
和num2
。
因此,如果op
的值是字符串"+"
,则_operationFunction[op]
返回一个对委托的引用,该引用实质上由lambda表达式描述:
(fst,snd) => (fst + snd)
然后将此引用指向的“函数”应用于参数num1
和num2
。
您可以在Func<T1,T2,TResult>上阅读更多有关代码中使用的代码的信息。