2008-10-15 19 views
5

所以,我有以下的反射的方法:調用使用一個單獨的對象

public class Singleton 
{ 

    private Singleton(){} 

    public static readonly Singleton instance = new Singleton(); 

    public string DoSomething(){ ... } 

    public string DoSomethingElse(){ ... } 

} 

使用反射我怎麼能調用DoSomething的方法?

我想問的原因是我將方法名稱存儲在XML中並動態地創建UI。例如,我動態地創建一個按鈕,並告訴它點擊按鈕時通過反射調用什麼方法。在某些情況下,它會是DoSomething,或者在其他情況下,它會是DoSomethingElse。

回答

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

非常感謝。這樣可行。除了找不到Types.Empty。 你的意思是Type.EmptyTypes? – Crippeoblade 2008-10-15 12:40:03

4

偉大的工作。謝謝。

對於不能引用遠程程序集的情況,稍做修改的方法也是如此。我們只需要知道基本的東西,例如類全名(即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);} 
相關問題