飞扬的Blog
主页
登录
c#提供函数名文本调用函数
"date"
:
"2020-11-22 02:50:26"
"classfiy"
:
"c#"
"author"
:
"飞扬"
"viewTimes"
:
260
返回
##模型 ``` public class CallModel { public string MethodName { get; set; } public object[] Params { get; set; } } ``` ##主要代码 ``` void NameCallMethod(CallModel input) { try { //获取父类的Type Type classType = MethodBase.GetCurrentMethod().DeclaringType; //获取方法,BindingFlags参数1忽略大小写,2是public方法,3是static方法 //这里属性必须匹配,否则找不到 var method = classType.GetMethod(input.MethodName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static); if (method == null) return; //获取方法的参数 var methodParams = method.GetParameters(); if (input.Params != null) { //判断方法参数数量和传过来的是否一致 if (methodParams.Length != input.Params.Length) return; for (int i = 0; i < methodParams.Length; i++) { //参数类型自动转换 //参数类型不匹配会导致错误,这里自动转换参数类型 //还有在部分情况下object类型的int整数会识别成long,比如web传过来的参数 var converter = TypeDescriptor.GetConverter(methodParams[i].ParameterType); input.Params[0] = converter.ConvertFromString(input.Params[i].ToString()); } } //调用方法 method?.Invoke(null, input.Params); //有返回值的函数 //比如返回值是string var result = (string)method?.Invoke(null, input.Params); } catch (Exception ex) { Console.WriteLine(ex.ToString()) } } ``` ##测试调用 ``` static class Program { static void Main() { var model = new JsCallModel { MethodName = "test", Params = new object[] { 1, "true" } }; //假装这个方法在当前类里【手动狗头】 NameCallMethod(model); } //要调用的方法 public static Test(string a, bool b) { Console.WriteLine($"a={a}, b={b}"); } } ```