【问题标题】:How to link a string key to a function in a c# dictionary如何将字符串键链接到 C# 字典中的函数
【发布时间】:2022-06-19 02:25:49
【问题描述】:

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

我想到了这样的代码:

private string name;

void function1()
    {
    // code
    }

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

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

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

感谢您的回答!

【问题讨论】:

  • 这能回答你的问题吗? C# Store functions in a Dictionary
  • ...添加到 Yong 的精细链接,以防链接的标题具有欺骗性,请注意作者在接受的 答案中的最后一点“如果您的函数没有返回值使用System.Action&lt;&gt;"

标签: c# unity3d


【解决方案1】:

您使用操作,例如Action 如果不返回值,Func 返回值。两者都定义有多个输入。所以你可以做 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)}");

【讨论】:

    【解决方案2】:

    这里有一些例子:

    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>>();
    
    【解决方案3】:
    //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();
     }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 2020-08-16
      • 2020-09-20
      • 2015-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多