I’m working on some existing code. After a few hours, I’ve boiled this problem down to a method picker class. I find this class to be difficult to follow. Is it possible to achieve this type of method picking functionality in a simple way?
public class MethodPicker
{
private delegate string SomeFunc(MethodPicker item);
static readonly Dictionary<string, SomeFunc> test = new Dictionary<string, SomeFunc>();
static MethodPicker()
{
test.Add("key1", Func1);
test.Add("key2", Func2);
test.Add("key3", Func3);
}
public string RunTest(string Name)
{
string somestring = test[Name].Invoke(this);
return somestring;
}
public static string Func1(MethodPicker entity)
{
return "func1 runs";
}
public static string Func2(MethodPicker entity)
{
return "func2 runs";
}
public static string Func3(MethodPicker entity)
{
return "func3 runs";
}
}
Well this would be a simpler solution..
It also highlights what is a potential problem in the dictionary solution as you have no proper error handling if the key/name does not exist in the dictionary. In your solution it would cause a NullPointerException here:
string somestring = test[Name].Invoke(this);test[Name]would be return null…