2008-10-15 9 views
5

Vì vậy, tôi có như sau:Gọi một phương pháp sử dụng phản ánh trên một đối tượng singleton

public class Singleton 
{ 

    private Singleton(){} 

    public static readonly Singleton instance = new Singleton(); 

    public string DoSomething(){ ... } 

    public string DoSomethingElse(){ ... } 

} 

Sử dụng phản chiếu làm thế nào tôi có thể gọi phương pháp DoSomething?

Lý do tôi hỏi là vì tôi lưu trữ tên phương thức trong XML và tự động tạo giao diện người dùng. Ví dụ tôi đang tự động tạo một nút và cho nó biết phương thức nào để gọi thông qua sự phản chiếu khi nút được nhấn. Trong một số trường hợp, nó sẽ là DoSomething hoặc trong một số trường hợp khác, nó sẽ là DoSomethingElse.

Trả lời

11

chưa được kiểm tra, nhưng nên làm việc ...

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

thankyou tuyệt vời. Điều đó hoạt động. Ngoại trừ không thể tìm thấy Types.Empty. Bạn có nghĩa là Type.EmptyTypes không? – Crippeoblade

4

Làm tốt lắm. Cảm ơn.

Đây là cách tiếp cận tương tự với sửa đổi nhỏ đối với trường hợp người ta không thể tham chiếu đến cụm từ xa. Chúng ta chỉ cần biết những thứ cơ bản như tên đầy đủ của lớp (ví dụ namespace.classname và đường dẫn đến assembly từ xa).

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