如何將類和方法名稱傳遞爲字符串並調用該類的方法?如何在.NET中動態調用類的方法?
像
void caller(string myclass, string mymethod){
// call myclass.mymethod();
}
感謝
如何將類和方法名稱傳遞爲字符串並調用該類的方法?如何在.NET中動態調用類的方法?
像
void caller(string myclass, string mymethod){
// call myclass.mymethod();
}
感謝
你將要使用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");
}
}
現在,這是一個非常簡單的例子,沒有錯誤檢查,如果類型住在另一個組件,但我認爲也忽略了喜歡做什麼更大的問題這應該讓你在正確的軌道上。
事情是這樣的:
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中是一定的你真正需要的方法修改綁定標誌。
你這樣做的理由是什麼?更可能的是,您可以在沒有反射的情況下執行此操作,直至幷包括動態組裝加載。
只要程序集加載並且typename是裝配限定的,您就是金。 – 2009-07-13 15:52:32
嗯......我',找到你的例子返回null在「Type.GetType(myclass);」 – pistacchio 2009-07-13 15:52:58