I have a message coming into my C# app which is an object serialized as JSON, when i de-serialize it I have a "Name" string
and a "Payload" string[]
, I want to be able to take the "Name" and look it up in a function dictionary, using the "Payload" array as its parameters and then take the output to return to the client sending the message, is this possible in C#?
I've found a stack overflow answer here where the second part seems plausible but i don't know what I'm referencing with State
Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.
In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.
It is flexible in that it allows a dictionary to contain keys of a wide variety of types. For example, the same dictionary can contain keys that are integers, floats, tuples, booleans, strings, and other types.
It sounds like you probably want something like:
Dictionary<string, Func<string[], int>> functions = ...;
This is assuming the function returns an int
(you haven't specified). So you'd call it like this:
int result = functions[name](parameters);
Or to validate the name:
Func<string[], int> function; if (functions.TryGetValue(name, out function)) { int result = function(parameters); ... } else { // No function with that name }
It's not clear where you're trying to populate functions
from, but if it's methods in the same class, you could have something like:
Dictionary<string, Func<string[], int>> functions = new Dictionary<string, Func<string[], int>> { { "Foo", CountParameters }, { "Bar", SomeOtherMethodName } }; ... private static int CountParameters(string[] parameters) { return parameters.Length; } // etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With