代码之家  ›  专栏  ›  技术社区  ›  Crippeoblade

使用单例对象上的反射调用方法

  •  5
  • Crippeoblade  · 技术社区  · 18 年前

    因此,我有以下几点:

    public class Singleton
    {
    
      private Singleton(){}
    
      public static readonly Singleton instance = new Singleton();
    
      public string DoSomething(){ ... }
    
      public string DoSomethingElse(){ ... }
    
    }
    

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

    2 回复  |  直到 18 年前
        1
  •  11
  •   Jon Skeet    18 年前

    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);
    
        2
  •  4
  •   nasser    16 年前

    干得好。谢谢

    对于不能引用远程程序集的情况,这里也有同样的方法,只需稍加修改。我们只需要知道一些基本的东西,比如类fullname(即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);}