/// <summary> /// 根据类型信息创建对象,该对象即使没有公有的构造方法,也可以创建实例 /// </summary> /// <param name="type">创建类型时的类型信息</param> /// <param name="constructorParams">创建实例的初始化参数</param> /// <returns>实例对象</returns> /// <remarks>运用晚绑定方式动态创建一个实例</remarks> public static object CreateInstance(System.Type type, params object[] constructorParams) { ExceptionHelper.FalseThrow <ArgumentNullException>(type != null, "type"); ExceptionHelper.FalseThrow <ArgumentNullException>(constructorParams != null, "constructorParams"); BindingFlags bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; try { return(Activator.CreateInstance(type, bf, null, constructorParams, null)); } catch (TargetInvocationException ex) { Exception realEx = ExceptionHelper.GetRealException(ex); string message = type.AssemblyQualifiedName + ":" + realEx.Message; throw new TargetInvocationException(message, realEx); } }
/// <summary> /// 根据类型信息,通过反射构造此类型,并且根据构造参数名称找到最匹配的构造方法,然后调用构造方法 /// </summary> /// <param name="type"></param> /// <param name="constructorParams"></param> /// <returns></returns> public static object CreateInstance(System.Type type, NameValueCollection constructorParams) { ExceptionHelper.FalseThrow <ArgumentNullException>(type != null, "type"); ExceptionHelper.FalseThrow <ArgumentNullException>(constructorParams != null, "constructorParams"); BindingFlags bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; try { ConstructorInfo ci = (ConstructorInfo)type.GetConstructors(bf).GetMatchedMethodInfoByParameterNames(constructorParams.AllKeys); ExceptionHelper.FalseThrow(ci != null, "不能找到类型{0}的构造方法", type.AssemblyQualifiedName); return(ci.Invoke(constructorParams)); } catch (TargetInvocationException ex) { Exception realEx = ExceptionHelper.GetRealException(ex); string message = type.AssemblyQualifiedName + ":" + realEx.Message; throw new TargetInvocationException(message, realEx); } }