c# - 字典中的函数,这段代码是如何工作的?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));
解决方案
这(以及其他表达式,with =>
)
(fst, snd) => (fst + snd)
是一个lambda 表达式。
字典中的 lambda 表达式表示整数之间的算术运算。因此,对于加法 (+)、乘法 (*)、减法 (-) 和除法 (/) 这四种操作中的每一种,都提供了一个 lambda 表达式来描述这些操作。
当我们编写以下内容时:
_operationFunction[op](num1, num2)
获取与键关联的字典的值,op
然后将返回的函数(值)应用于整数num1
和num2
。
因此,如果 的值为op
string "+"
,则_operationFunction[op]
返回对委托的引用,本质上由 lambda 表达式描述:
(fst, snd) => (fst + snd)
然后这个引用指向的“函数”被应用于参数num1
和num2
。
您可以在Func<T1,T2,TResult>阅读更多重新分级代码中使用的内容。
推荐阅读
- java - Seleniuim with java:获取 Excel 文件数据未在控制台上获得完整输出-
- javascript - 从成功的正则表达式中获取字符串?
- javascript - 如何使用react js检测android / ios手机中是否按下了后退按钮
- z3 - 在 SMT 中表示无关位向量
- c++ - 我可以使用 std::copy 复制到 stringstream 吗
- terraform - 如何保持 Terraform aws_security_group 的使用 DRY
- python - 我想对熊猫数据框中的列值进行编码
- python - Python plt.axis('Equal') xlim
- php - 未显示最近输入的建议框
- ios - 如何在项目中添加自定义 iOS 框架的引用(而不是副本)