Reputation: 117
Sorry for the newbie question, but how would you:
javascript version would be like:
function LookUpAndDo(num, funcName) {
const dictionary = {
myFunc: (x) => { return x},
}
const runThis = dictionary[funcName];
return runThis(num)
}
LookUpAndDo(5, "myFunc");
// returns 5
Upvotes: 0
Views: 254
Reputation: 8824
This method is pretty straightforward to convert to C#
private T LookUpAndDo<T>(T param, string funcName)
{
var dict = new Dictionary<string, Func<T, T>>{
{ "myFunc", x => x }
};
var func = dict[funcName];
return func.Invoke(param);
}
And you may invoke it as LookUpAndDo(5, "myFunc");
In the case Func parameter and return types does not match, then you'd have to specify both types in the generic method:
private TResult LookUpAndDo<T, TResult>(T param, string funcName)
{
var dict = new Dictionary<string, Func<T, TResult>>{
{ "myFunc", x => x.ToString() }
};
var func = dict[funcName];
return func.Invoke(param);
}
And since C# can't infer return types, you'd have to call passing both type parameters, as: LookUpAndDo<int, string>(5, "myFunc");
Upvotes: 1