通过将函数名称作为字符串传递来动态调用任何函数

2024-01-02

如何自动创建实例并动态执行其函数?

Thanks

编辑:也需要一个传递参数的选项。谢谢


您只想调用无参数构造函数来创建实例吗?类型也指定为字符串,还是可以将其设为泛型方法?例如:

// 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);
}

or

public void Invoke<T>(string methodName) where T : new()
{
    T instance = new T();
    MethodInfo method = typeof(T).GetMethod(methodName);
    method.Invoke(instance, null);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过将函数名称作为字符串传递来动态调用任何函数 的相关文章

随机推荐