通过传递函数名作为字符串动态调用任何函数 [英] Dynamically invoking any function by passing function name as string
本文介绍了通过传递函数名作为字符串动态调用任何函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何获得自动化的实例创建,其函数动态执行的过程吗?
How do I automate the process of getting an instance created and its function executed dynamically?
感谢
编辑:需要一个选项来传递参数了。谢谢
Need an option to pass parameters too. Thanks
推荐答案
你只是想调用一个参数的构造函数来创建实例?被指定为一个字符串,以及类型,或者你可以把它一个通用的方法是什么?例如:
Do you just want to call a parameterless constructor to create the instance? Is the type specified as a string as well, or can you make it a generic method? For example:
// All error checking omitted. In particular, check the results
// of Type.GetType, and make sure you call it with a fully qualified
// type name, including the assembly if it's not in mscorlib or
// the current assembly. The method has to be a public instance
// method with no parameters. (Use BindingFlags with GetMethod
// to change this.)
public void Invoke(string typeName, string methodName)
{
Type type = Type.GetType(typeName);
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod(methodName);
method.Invoke(instance, null);
}
或
public void Invoke<T>(string methodName) where T : new()
{
T instance = new T();
MethodInfo method = typeof(T).GetMethod(methodName);
method.Invoke(instance, null);
}
这篇关于通过传递函数名作为字符串动态调用任何函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文