如何使用C#在映射容器中编写带有lambda表达式的std::函数

How to write a std::function with lambda expression in a map container using C#?

本文关键字:lambda 表达式 函数 std 何使用 映射      更新时间:2023-10-16

如何将下面的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#代码:

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