/// <summary> /// 要执行的方法,根据方法名、参数数量 /// </summary> /// <param name="type">要调用的对象的类型</param> /// <param name="p"></param> /// <returns></returns> private static MethodInfo getMethod(Type type, Letter p) { //1、先判断方法是否存在 List <MethodInfo> methods = new List <MethodInfo>(); foreach (MethodInfo mi in type.GetMethods()) { if (p.MethodName.Equals(mi.Name, StringComparison.CurrentCultureIgnoreCase)) { methods.Add(mi); } } if (methods.Count < 1) { throw new Exception(string.Format("调用方法'{0}.{1}'不存在", p.ClassName, p.MethodName)); } //2、判断方法的参数名称,是否与传递来的参数名称匹配,参数数量必须匹配 //只有一个参数,且类型是Letter MethodInfo mbLetter = null; for (int i = 0; i < methods.Count; i++) { ParameterInfo[] pis = methods[i].GetParameters(); if (pis.Length == 1 && p.GetType().FullName.Equals(pis[0].ParameterType.FullName)) { mbLetter = methods[i]; methods.Remove(methods[i]); break; } } MethodInfo method = null; foreach (MethodInfo mi in methods) { //2-1、判断参数个数是否相同 int paraCount = 0; foreach (ParameterInfo pi in mi.GetParameters()) { if (!pi.IsOut) { paraCount++; } } //方法的参数个数,和传参的参数个数,必须相等 if (paraCount == p.Params.Count) { method = mi; break; } } //2-2、判断参数名称与传递来的参数名称是否一致 if (method != null) { bool ismatch = true; //是否匹配 foreach (ParameterInfo pi in method.GetParameters()) { //如果参数是Parameter类型,则跳过匹配 if (p.GetType().FullName.Equals(pi.ParameterType.FullName)) { continue; } //只要有一个参数不匹配,即中断 if (!p.ExistParameter(pi.Name)) { ismatch = false; break; } } if (!ismatch) { method = null; } } if (method == null) { method = mbLetter; } if (method == null) { throw new Exception( string.Format("所调用方法'{0}.{1}'的参数名称与实际传参不匹配;实际传参:{2}", type.FullName, p.MethodName, p.ToString() == string.Empty ? "null" : p.ToString())); } return(method); }