/// <summary>
/// 执行指定方法
/// </summary>
/// <param name="funName">方法名</param>
/// <param name="type">获取指定类的类型,如:Type type = class1.GetType()</param>
private void ExecuteSpecifiedMethod(string funName, Type type)
{
Class1 class1 = new Class1();//实例化类对象
Type type = class1.GetType();//获取指定类的类型
MethodInfo[] methodInfos = type.GetMethods();//获取该类型的所有公共方法
foreach (MethodInfo method in methodInfos)//遍历方法找到指定方法
{
if (method.Name == funName)//检验是否和指定方法名相同 Name:仅包含方法名称
method.Invoke(class1, new object[] { 2, 2 });//执行该方法,class1为类的实例 object数组为执行该方法的参数数组
}
}
使用反射执行指定名称的方法
最新推荐文章于 2021-11-07 13:16:22 发布