我想知道在c#中是否有一种方法来执行一个方法,如果我们在一个字符串中只有它的名字?
string methodname="method"
this.RunMethod(methodname)像这样的吗?
谢谢:)
发布于 2012-04-26 21:44:14
您可以创建一个泛型方法,通过它们的名称在任何您想要的实例上调用方法:
public void RunMethodOn(object obj, String methodName,params Object[] args)
{
if(obj != null)
{
System.Reflection.MethodInfo method = null;
method = obj.GetType().GetMethod(methodName);
if (method != null)
method.Invoke(obj, args);
}
}并使用它在您自己的实例上调用一个方法,如下所示:
public void RunMethod(String methodName,params Object[] args)
{
ExecuteOn(this, methodName, args);
}发布于 2012-04-26 21:38:39
试试这个:
Type t = Type.GetType(typeName);
t.InvokeMember("method", BindingFlags.InvokeMethod | BindingFlags.Public, null, null, null);发布于 2012-04-26 21:38:01
就像这样
Type type = GetType("MyType");
MethodInfo methodInfo = type.GetMethod(methodName);
methodInfo.Invoke()https://stackoverflow.com/questions/10334588
复制相似问题