如何将类和方法名称传递为字符串并调用该类的方法?如何在.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