如何 link c# 字典中函数的字符串键

How to link a string key to a function in a c# dictionary

我目前正在使用 Unity 和 C# 进行编程,但我无法使用字典将字符串值链接到函数。

我认为代码如下所示:

private string name;

void function1()
    {
    // code
    }

private Dictionary<string, ?function?> nameToFunction = new Dictonary<string, ?function?>();
// The part between interogation marks being unknown to me

// Trying to call the funtion with the name
nameToFunction[name]

如果我的问题不是相对的,或者如果有我没有想到的更简单的解决方案,我很抱歉,但我正在开始学习编程。

感谢您的回答!

这里有一些例子:

private Dictionary<string, Action> actionDict = new Dictionary<string, Action>();

private Dictionary<string, Action<int>> actionParamDict = new Dictionary<string, Action<int>>();

private Dictionary<string, Func<int>> funcDict = new Dictionary<string, Func<int>>();

private Dictionary<string, Func<int, string>> funcParamDict = new Dictionary<string, Func<int, string>>();
//create dict with var objects s0, s1, s2 dynamically 
Dictionary<String, Object> dictionary = new Dictionary<String, Object>();
for(int i=0; i<sWPaths.Length-1; i++) {
string name = String.Format("s{0}", i);
dictionary[name] = i.ToString();
}

foreach (string p in found){
//change to your desired variable using string.format method
if(dictionary.Contains[p]) {
dictionary[p] = found.ToString();
 }
}

您使用操作,例如Action if not returning a value, Func return 一个值。两者都定义有多个输入。例如,您可以执行 Func 和 Action

这里有几个例子:

var dict = new Dictionary<string, Action>();
dict.Add("Hello", () => Console.WriteLine("Hello"));
dict.Add("Goodbye", () => Console.WriteLine("Goodbye"));
dict["Hello"]();
dict["Goodbye"]();

var dict2 = new Dictionary<string, Action<string>>();
dict2.Add("HelloName", (name) => Console.WriteLine($"Hello {name}"));
dict2["HelloName"]("Fred");

var dict3 = new Dictionary<string, Func<int, int, int>>();
dict3.Add("ADD", (n1, n2) => n1 + n2);
dict3.Add("SUBTRACT", (n1, n2) => n1 - n2);
Console.WriteLine($"{dict3["ADD"](5, 10)}");
Console.WriteLine($"{dict3["SUBTRACT"](10, 5)}");