通过调用一个singleton对象上反射的方法 [英] Invoking a method using reflection on a singleton object

查看:215
本文介绍了通过调用一个singleton对象上反射的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下几点:

public class Singleton
{

  private Singleton(){}

  public static readonly Singleton instance = new Singleton();

  public string DoSomething(){ ... }

  public string DoSomethingElse(){ ... }

}

使用反射我怎么能调用DoSomething的方法?

Using reflection how can I invoke the DoSomething Method?

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

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.

推荐答案

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

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

这篇关于通过调用一个singleton对象上反射的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆