通过将函数名称作为字符串传递来动态调用任何函数 [英] Dynamically invoking any function by passing function name as string

查看:33
本文介绍了通过将函数名称作为字符串传递来动态调用任何函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆