5

所以我有以下内容:

public class Singleton
{

  private Singleton(){}

  public static readonly Singleton instance = new Singleton();

  public string DoSomething(){ ... }

  public string DoSomethingElse(){ ... }

}

使用反射如何调用 DoSomething 方法?

我问的原因是因为我将方法名称存储在 XML 中并动态创建 UI。例如,我正在动态创建一个按钮,并告诉它在单击按钮时通过反射调用什么方法。在某些情况下,它会是 DoSomething,或者在其他情况下,它会是 DoSomethingElse。

4

2 回答 2

11

未经测试,但应该可以工作......

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);
于 2008-10-15T12:20:50.543 回答
4

做得好。谢谢。

对于无法引用远程程序集的情况,这是相同的方法,只需稍作修改。我们只需要知道基本的东西,例如类全名(即命名空间.类名和远程程序集的路径)。

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);}
于 2010-02-05T07:42:37.187 回答