Home > Net >  How to link a string key to a function in a c# dictionary
How to link a string key to a function in a c# dictionary

Time:05-21

I am currently programming using Unity and C#, and I have trouble linking a string value to a function using a dictionnary.

I think of a code looking like this :

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]

I am sorry if my question isn't relative, or if there are simpler solutions I haven't thought of, but I am starting to learn programming.

Thanks for your answers !

CodePudding user response:

Here are some examples:

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>>();

CodePudding user response:

//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();
 }
}

CodePudding user response:

You use Action e.g. Action<input type1, input type 2> if not returning a value, and Func<input type1, input type2, output type> to return a value. Both are defined with multiple numbers of inputs. So you could do Func<int,int,int,bool> for example, and Action<int,int,bool,string,string>

Here's a few examples:

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)}");
  • Related