Invoking a method using reflection on a singleton object
c#, reflection, singleton
Solution
Untested, but should work...
string methodName = "DoSomething"; // e.g. read from XML
MethodInfo method = typeof(Singleton).GetMethod(methodName);
FieldInfo field = typeof(Singleton).GetField("instance",
BindingFlags.Static | BindingFlags.Public);
object instance = field.GetValue(null);
method.Invoke(instance, Type.EmptyTypes);
Problem
So I have the following: ``` public class Singleton { private Singleton(){} public static readonly Singleton instance = new Singleton(); public string DoSomething(){ ... } public string DoSomethingElse(){ ... } } ``` Using reflection how can I invoke the DoSomething Method? Reason I ask is because I store the method names in XML and dynamically create the UI. For example I'm dynamically creating a button and telling it what method to call via reflection when the button is clicked. In some cases it would be DoSomething or in others it would be DoSomethingElse.