【问题标题】:How to write a std::function with lambda expression in a map container using C#?如何使用 C# 在地图容器中编写带有 lambda 表达式的 std::function?
【发布时间】:2015-12-01 16:16:02
【问题描述】:

如何将下面的 C++ 代码重写为 C#?

std::string someVariable;

std::map<std::string, std::function<void (std::string)>> myMap;

myMap.insert(std::make_pair("someText", [&](std::string input){someVariable = input;});

我尝试过和代表一起玩,但我还不太了解。

【问题讨论】:

  • 你在 c# 中的 lambda 看起来像这样:(string input) =&gt; { someVariable = input; } 或为简洁起见(x) =&gt; someVariable = x

标签: c# c++ lambda delegates std-function


【解决方案1】:

不知道为什么要这样做,但这是等效的 C# 代码:

string someVariable = string.Empty;

Dictionary<string, Action<string>> map = new Dictionary<string, Action<string>>();

map.Add("someText", (input) => someVariable = input);

map["someText"]("someInput");

Console.WriteLine(someVariable);

输出:

someInput

演示:https://ideone.com/03sbqH

【讨论】:

  • 感谢您的快速回复!我会试试这个。
猜你喜欢
  • 2023-01-20
  • 2022-01-19
  • 1970-01-01
  • 2011-04-22
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多