views:

1012

answers:

2

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.

+4  A: 

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);
Jon Skeet
great thankyou. That works. Except couldn't find Types.Empty. Do you mean Type.EmptyTypes?
Crippeoblade
Yes, I do. Will fix.
Jon Skeet
A: 

Great job. Thanks.

Here's the same approach with slight modification for cases that one can't have a reference to the remote assembly. We just need to know basic things such as the class fullname (i.e namespace.classname and the path to the remote assembly).

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);}
nasser