/// <summary> /// Calls the specified method and returns the result of execution /// </summary> /// <param name="type">Then Instance objects.</param> /// <param name="container">Then Instance objects.</param> /// <param name="name">The name of the method.</param> /// <param name="args">The parameter of the method.</param> /// <returns>The result of execution.</returns> public static object CallMethod(Type type, object container, string name, object[] args) { Type[] types = new Type[args.Length]; bool hasNullValue = false; for (int i = 0; i < args.Length; i++) { if (args[i] != null) { types[i] = args[i].GetType(); } else { hasNullValue = true; } } MethodInfo method = DynamicHelpers.GetMethod(type, name, types); if (method != null) { //if (hasParam) //{ // Array arr; // if (types.Length - 1 == args.Length) // { // arr = null; // } // else // { // arr = Array.CreateInstance(types[types.Length - 1].GetElementType(), args.Length - types.Length + 1); // for (int i = types.Length - 1; i < args.Length; i++) // { // arr.SetValue(args[i], i - (types.Length - 1)); // } // object[] newArgs = new object[types.Length]; // for (int i = 0; i < newArgs.Length - 1; i++) // { // newArgs[i] = args[i]; // } // newArgs[newArgs.Length - 1] = arr; // return method.Invoke(container, newArgs); // } //} var pi = method.GetParameters(); if (types.Length == 1 && types[0] == typeof(Dictionary <object, object>) && (pi.Length != 1 || !pi[0].ParameterType.IsSubclassOf(typeof(IDictionary)))) { args = DynamicHelpers.ChangeParameters((Dictionary <object, object>)args[0], pi); } else if (hasNullValue) { for (int i = 0; i < args.Length; i++) { if (args[i] == null && !pi[i].ParameterType.IsClass && pi[i].DefaultValue != DBNull.Value) { args[i] = pi[i].DefaultValue; } //else //{ // args[i] = DefaultForType(pi[i].ParameterType); //} } } return(method.Invoke(container, args)); } return(null); }
/// <summary> /// 实参是否匹配形参 /// </summary> /// <param name="pi">形参</param> /// <param name="args">实参</param> /// <returns>bool</returns> public static bool IsMatch(ParameterInfo[] pi, Type[] args) { if (pi.Length != args.Length) { return(false); } //暂不考虑可选参数,默认参数,param参数 for (int i = 0; i < args.Length; i++) { if (args[i] == null) { continue; } if (args[i] != pi[i].ParameterType && !args[i].IsSubclassOf(pi[i].ParameterType) && !DynamicHelpers.CanChange(args[i], pi[i].ParameterType)) { return(false); } } return(true); }