Calling a method using reflection on a singleton object

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 call the DoSomething method?

The reason I'm asking for is because I store the method names in XML and dynamically create a user interface. For example, I dynamically create a button and tell which method to call through reflection when the button is clicked. In some cases it will be DoSomething, or in others it will be DoSomethingElse.

+5
source share
2 answers

Unconfirmed, 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);
+11
source

Great job. Thank you

, . , (i.e namespace.classname ).

static void Main(string[] args)
    {
        Assembly asm = null;
        string assemblyPath = @"C:\works\...\StaticMembers.dll" 
        string classFullname = "StaticMembers.MySingleton";
        string doSomethingMethodName = "DoSomething";
        string doSomethingElseMethodName = "DoSomethingElse";

        asm = Assembly.LoadFrom(assemblyPath);
        if (asm == null)
           throw new FileNotFoundException();


        Type[] types = asm.GetTypes();
        Type theSingletonType = null;
        foreach(Type ty in types)
        {
            if (ty.FullName.Equals(classFullname))
            {
                theSingletonType = ty;
                break;
            }
        }
        if (theSingletonType == null)
        {
            Console.WriteLine("Type was not found!");
            return;
        }
        MethodInfo doSomethingMethodInfo = 
                    theSingletonType.GetMethod(doSomethingMethodName );


        FieldInfo field = theSingletonType.GetField("instance", 
                           BindingFlags.Static | BindingFlags.Public);

        object instance = field.GetValue(null);

        string msg = (string)doSomethingMethodInfo.Invoke(instance, Type.EmptyTypes);

        Console.WriteLine(msg);

        MethodInfo somethingElse  = theSingletonType.GetMethod(
                                       doSomethingElseMethodName );
        msg = (string)doSomethingElse.Invoke(instance, Type.EmptyTypes);
        Console.WriteLine(msg);}
+4

All Articles