2009-07-13 25 views

回答

26

你將要使用reflection

下面是一個簡單的例子:

using System; 
using System.Reflection; 

class Program 
{ 
    static void Main() 
    { 
     caller("Foo", "Bar"); 
    } 

    static void caller(String myclass, String mymethod) 
    { 
     // Get a type from the string 
     Type type = Type.GetType(myclass); 
     // Create an instance of that type 
     Object obj = Activator.CreateInstance(type); 
     // Retrieve the method you are looking for 
     MethodInfo methodInfo = type.GetMethod(mymethod); 
     // Invoke the method on the instance we created above 
     methodInfo.Invoke(obj, null); 
    } 
} 

class Foo 
{ 
    public void Bar() 
    { 
     Console.WriteLine("Bar"); 
    } 
} 

現在,這是一個非常簡單的例子,沒有錯誤檢查,如果類型住在另一個組件,但我認爲也忽略了喜歡做什麼更大的問題這應該讓你在正確的軌道上。

+0

只要程序集加載並且typename是裝配限定的,您就是金。 – 2009-07-13 15:52:32

+0

嗯......我',找到你的例子返回null在「Type.GetType(myclass);」 – pistacchio 2009-07-13 15:52:58

8

事情是這樣的:

public object InvokeByName(string typeName, string methodName) 
{ 
    Type callType = Type.GetType(typeName); 

    return callType.InvokeMember(methodName, 
        BindingFlags.InvokeMethod | BindingFlags.Public, 
        null, null, null); 
} 

你應該根據你想打電話,以及檢查Type.InvokeMember方法在MSDN中是一定的你真正需要的方法修改綁定標誌。

-3

你這樣做的理由是什麼?更可能的是,您可以在沒有反射的情況下執行此操作,直至幷包括動態組裝加載。