【问题标题】:Invoking a method using reflection on a singleton object在单例对象上使用反射调用方法
【发布时间】:2008-10-15 12:11:08
【问题描述】:

所以我有以下内容:

public class Singleton
{

  private Singleton(){}

  public static readonly Singleton instance = new Singleton();

  public string DoSomething(){ ... }

  public string DoSomethingElse(){ ... }

}

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

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

【问题讨论】:

    标签: c# reflection singleton


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢。这样可行。除了找不到 Types.Empty。你是说 Type.EmptyTypes 吗?
    【解决方案2】:

    干得好。谢谢。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-15
      • 2013-03-23
      • 1970-01-01
      • 2023-04-05
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      相关资源
      最近更新 更多