如何使用字典中的 Func

发布于 2025-01-16 11:42:28 字数 344 浏览 2 评论 0原文

我想做的是为特定的键调用特定的函数。 例如,如果 is 键是“+”,我想调用 Sum 函数。 我已经创建了一个字典,并添加了一个键和一个函数。

Func<int, int, int> Sum = (a, b) => a + b;
Dictionary<char, Func<int, int, int>> operations = new Dictionary<char, Func<int, int, int>>()
operations.Add('+', Sum);

我不明白如何将值传递给我的 Sum Func,以及如何将答案存储在某处。

What I'm trying to do, is to call a specific function for a specific Key.
For example, if the is key is '+', I want to call Sum function.
I already created a Dictionary, and added a Key and a function.

Func<int, int, int> Sum = (a, b) => a + b;
Dictionary<char, Func<int, int, int>> operations = new Dictionary<char, Func<int, int, int>>()
operations.Add('+', Sum);

I don't understand how to pass a values to my Sum Func, and how to store an answer somewhere.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷雾森÷林ヴ 2025-01-23 11:42:28

我不明白如何将值传递给我的 Sum Func,以及如何将答案存储在某处。

var operation = operations['+'];
var result = operation(1, 2); // yields 3

(fiddle)

如果你想强调操作是委托而不是“常规”方法,您可以编写 operation.Invoke(1, 2) 而不是 operation(1, 2)

I don't understand how to pass a values to my Sum Func, and how to store an answer somewhere.

var operation = operations['+'];
var result = operation(1, 2); // yields 3

(fiddle)

If you want to emphasize that operation is a delegate rather than a "regular" method, you can write operation.Invoke(1, 2) instead of operation(1, 2).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文