C# dictionary store action/method
Solution 1
You need to create a dictionary<string, Action>
, this would be for no parameters.
e.g.
static class MyActions {
static Dictionary<string,Action> wibble = new Dictionary<string,Action>();
}
I've used static, its not necessary if you can pass the reference around/retrieve the reference.
then to add action...
MyActions.wibble["123456789"] = () => { // do action };
or reference a no parameter method
MyActions.wibble["123456789"] = () => MyMethod;
then to call it;
MyActions.wibble["123456789"]()
Assuming the key exists, you can use try get or even MyActions.wibble["123456789"]?.Invoke()
If you need parameters, make the dictionary of type Action<T>
or Action<T1, T2>
etc depending on the number of parameters.
eg wibble = new Dictionary<string,Action<int>>()
and then wibble["123456789"] = x => {action with x}
and wibble["123456789"](42)
Solution 2
Sounds like a simple task. (Doesn't include sanity checks)
Dictionary<string,Action<object>> dict;
public Action<object> GetFunction(string key)
{
return dict[key];
}
public void CallFunction(string key, object parameter)
{
dict[key](parameter);
}
John
Updated on June 14, 2022Comments
-
John almost 2 years
I have a dictionary with
string
keys, e.g.123456789
. Now at some other point inside my application, I want my dictionary to look this key up and either run the method itself (stored along the key) or somehow return the function so I can manually add parameters. Is this even possible?-
SpruceMoose over 6 yearsYes. Why would it not be possible?
-
Manfred Radlwimmer over 6 yearsYes, quite simple actually. You can make the type of the value any delegate you want (e.g.
Action
,Predicate
, etc.). -
John over 6 yearsWhy would it not be possible to disable gravity? @Cal279
-
John over 6 yearsI thought of
Action<>
, but wondered if this is the right point to get this one started. -
Manfred Radlwimmer over 6 yearsBecause science is not that far yet. But lucky you - what you want is possible.
-
illug over 6 yearsHave a look at reflection
-
Manfred Radlwimmer over 6 yearsYes,
Action<>
can be stored within a dictionary. Upon retrieval you can execute it like a regular function, e.g.dict["123"](parameter)
-
Manfred Radlwimmer over 6 years@illug Always a good topic, but seems like overkill in this particular situation.
-
John over 6 yearsThanks, @ManfredRadlwimmer. I'll take a look at this.
-