/// <summary>通过字典参数调用</summary> /// <param name="obj"></param> /// <param name="parameters">参数数组</param> /// <returns></returns> public Object InvokeWithParams(Object obj, IDictionary parameters) { //// 没有传入参数 //if (parameters == null || parameters.Count < 1) return Invoke(obj, null); //! 注意:有可能没有传入参数,但是该方法是需要参数的,这个时候采用全部null的方法 // 该方法没有参数,无视外部传入参数 var pis = Method.GetParameters(); if (pis == null || pis.Length < 1) { return(Invoke(obj, null)); } Object[] ps = new Object[pis.Length]; for (int i = 0; i < pis.Length; i++) { Object v = null; if (parameters != null && parameters.Contains(pis[i].Name)) { v = parameters[pis[i].Name]; } ps[i] = TypeX.ChangeType(v, pis[i].ParameterType); } return(Handler.Invoke(obj, ps)); }
/// <summary>执行表达式,返回结果。参数名默认为p0/p1/p2/pn</summary> /// <param name="code"></param> /// <param name="parameters"></param> /// <returns></returns> public static Object Execute(String code, Object[] parameters) { if (parameters == null || parameters.Length < 1) { return(Execute(code)); } var se = Create(code); if (se != null && se.Method != null) { return(se.Invoke(parameters)); } var names = new String[parameters.Length]; for (int i = 0; i < names.Length; i++) { names[i] = "p" + i; } var types = TypeX.GetTypeArray(parameters); var dic = se.Parameters; for (int i = 0; i < names.Length; i++) { dic.Add(names[i], types[i]); } return(se.Invoke(parameters)); }
/// <summary>执行表达式,返回结果</summary> /// <param name="code">代码片段</param> /// <param name="parameters">参数名值对</param> /// <returns></returns> public static Object Execute(String code, IDictionary <String, Object> parameters) { if (parameters == null || parameters.Count < 1) { return(Execute(code)); } var ps = new Object[parameters.Count]; parameters.Values.CopyTo(ps, 0); var se = Create(code); if (se != null && se.Method != null) { return(se.Invoke(ps)); } var names = new String[parameters.Count]; parameters.Keys.CopyTo(names, 0); var types = TypeX.GetTypeArray(ps); var dic = se.Parameters; for (int i = 0; i < names.Length; i++) { dic.Add(names[i], types[i]); } return(se.Invoke(ps)); }
/// <summary>转换多个对象</summary> /// <typeparam name="TInterface"></typeparam> /// <param name="objects"></param> /// <returns></returns> public static TInterface[] Implement <TInterface>(params object[] objects) { if (objects == null) { throw new ArgumentNullException("objects"); } Type interfaceType = typeof(TInterface); ValidateInterfaceType(interfaceType); Type[] duckedTypes = new Type[objects.Length]; for (int i = 0; i < objects.Length; i++) { duckedTypes[i] = objects[i].GetType(); } Type[] duckTypes = GetDuckTypes(interfaceType, duckedTypes); TInterface[] ducks = new TInterface[objects.Length]; for (int i = 0; i < objects.Length; i++) { //ducks[i] = (TInterface)Activator.CreateInstance(duckTypes[i], objects[i]); ducks[i] = (TInterface)TypeX.CreateInstance(duckTypes[i], objects[i]); } return(ducks); }
public List <Type> FindPlugins(Type baseType) { // 如果type是null,则返回所有类型 List <Type> list = null; if (_plugins.TryGetValue(baseType, out list)) { return(list); } lock (_plugins) { if (_plugins.TryGetValue(baseType, out list)) { return(list); } list = new List <Type>(); foreach (var item in Types) { if (TypeX.Create(item).IsPlugin(baseType)) { list.Add(item); } } if (list.Count <= 0) { list = null; } _plugins.Add(baseType, list); return(list); } }
/// <summary>创建</summary> /// <param name="type">类型</param> /// <param name="name">名称</param> /// <param name="paramTypes">参数类型</param> /// <returns></returns> public static MethodInfoX Create(Type type, String name, Type[] paramTypes) { //var method = type.GetMethod(name, paramTypes); //if (method == null) method = type.GetMethod(name, DefaultBinding, null, paramTypes, null); //if (method == null) method = type.GetMethod(name, DefaultBinding | BindingFlags.IgnoreCase, null, paramTypes, null); //if (method == null && type.BaseType != typeof(Object)) return Create(type.BaseType, name, paramTypes); var method = TypeX.GetMethod(type, name, paramTypes); if (method == null) { return(null); } return(Create(method)); }
public override void SetValue(Object obj, Object value) { if (SetHandler == null) { throw new InvalidOperationException("不支持SetValue操作!"); } // 如果类型不匹配,先做类型转换 if (value != null && !Type.IsAssignableFrom(value.GetType())) { value = TypeX.ChangeType(value, Type); } SetHandler.Invoke(obj, value); }
/// <summary>转换单个对象</summary> /// <param name="obj"></param> /// <param name="interfaceType"></param> /// <returns></returns> public static Object Implement(Object obj, Type interfaceType) { if (obj == null) { throw new ArgumentNullException("obj"); } //Type duckedType = obj.GetType(); ValidateInterfaceType(interfaceType); Type duckType = GetDuckType(interfaceType, obj.GetType()); //return Activator.CreateInstance(duckType, obj); return(TypeX.CreateInstance(duckType, obj)); }
/// <summary>快速调用静态方法</summary> /// <typeparam name="TTarget">目标类型</typeparam> /// <typeparam name="TResult">返回类型</typeparam> /// <param name="name">名称</param> /// <param name="parameters">参数数组</param> /// <returns></returns> public static TResult Invoke <TTarget, TResult>(String name, params Object[] parameters) { if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } MethodInfoX mix = Create(typeof(TTarget), name, TypeX.GetTypeArray(parameters)); if (mix == null) { throw new XException("类{0}中无法找到{1}方法!", typeof(TTarget).Name, name); } return((TResult)mix.Invoke(null, parameters)); }
String GetName(Boolean isfull, Boolean includeDefType = true) { var method = _Method; var sb = new StringBuilder(); String name = null; if (includeDefType) { var type = method.DeclaringType ?? method.ReflectedType; if (type != null) { var tx = TypeX.Create(type); name = isfull ? tx.FullName : tx.Name; } else { name = ""; } } sb.AppendFormat("{0}.", name); sb.Append(method.Name); sb.Append("("); var ps = method.GetParameters(); for (int i = 0; i < ps.Length; i++) { if (i > 0) { sb.Append(","); } if (ps[i].ParameterType != null) { var tx = TypeX.Create(ps[i].ParameterType); name = isfull ? tx.FullName : tx.Name; } else { name = ""; } sb.AppendFormat("{0} {1}", name, ps[i].Name); } sb.Append(")"); return(sb.ToString()); }
String GetName(Boolean isfull) { Type type = Type; if (type.IsNested) { var tx = TypeX.Create(type.DeclaringType); return((isfull ? tx.FullName : tx.Name) + "." + type.Name); } else if (type.IsGenericType) { var sb = new StringBuilder(); var typeDef = type.GetGenericTypeDefinition(); var name = isfull ? typeDef.FullName : typeDef.Name; var p = name.IndexOf("`"); if (p >= 0) { sb.Append(name.Substring(0, p)); } else { sb.Append(name); } sb.Append("<"); var ts = type.GetGenericArguments(); for (int i = 0; i < ts.Length; i++) { if (i > 0) { sb.Append(","); } if (!ts[i].IsGenericParameter) { var tx = TypeX.Create(ts[i]); sb.Append(isfull ? tx.FullName : tx.Name); } } sb.Append(">"); return(sb.ToString()); } else { return(isfull ? type.FullName : type.Name); } }
public override Object Invoke(Object obj, params Object[] parameters) { if (parameters == null || parameters.Length <= 0) { return(Handler.Invoke(obj, null)); } else { // 预处理参数类型 var pis = Parameters; for (int i = 0; i < parameters.Length && i < pis.Length; i++) { parameters[i] = TypeX.ChangeType(parameters[i], pis[i].ParameterType); } return(Handler.Invoke(obj, parameters)); } }
/// <summary>获取方法</summary> /// <remarks>用于具有多个签名的同名方法的场合,不确定是否存在性能问题,不建议普通场合使用</remarks> /// <param name="type">类型</param> /// <param name="name">名称</param> /// <param name="paramTypes">参数类型数组</param> /// <returns></returns> public override MethodInfo GetMethod(Type type, String name, params Type[] paramTypes) { // 参数数组必须为空,或者所有参数类型都不为null,才能精确匹配 if (paramTypes == null || paramTypes.Length == 0 || paramTypes.All(t => t != null)) { var method = base.GetMethod(type, name, paramTypes); if (method != null) { return(method); } } // 任意参数类型为null,换一种匹配方式 if (paramTypes.Any(t => t == null)) { var ms = GetMethods(type, name, paramTypes.Length); if (ms == null || ms.Length == 0) { return(null); } // 对比参数 foreach (var mi in ms) { var ps = mi.GetParameters(); var flag = true; for (int i = 0; i < ps.Length; i++) { if (paramTypes[i] != null && !ps[i].ParameterType.IsAssignableFrom(paramTypes[i])) { flag = false; break; } } if (flag) { return(mi); } } } return(TypeX.GetMethod(type, name, paramTypes)); }
/// <summary>创建快速访问成员</summary> /// <param name="member"></param> /// <returns></returns> public static MemberInfoX Create(MemberInfo member) { if (member == null) { return(null); } switch (member.MemberType) { case MemberTypes.All: break; case MemberTypes.Constructor: return(ConstructorInfoX.Create(member as ConstructorInfo)); case MemberTypes.Custom: break; case MemberTypes.Event: return(EventInfoX.Create(member as EventInfo)); case MemberTypes.Field: return(FieldInfoX.Create(member as FieldInfo)); case MemberTypes.Method: return(MethodInfoX.Create(member as MethodInfo)); case MemberTypes.Property: return(PropertyInfoX.Create(member as PropertyInfo)); case MemberTypes.TypeInfo: case MemberTypes.NestedType: return(TypeX.Create(member as Type)); default: break; } return(null); }
public override void SetValue(Object obj, Object value) { // 如果类型不匹配,先做类型转换 if (value != null && !Type.IsAssignableFrom(value.GetType())) { value = TypeX.ChangeType(value, Type); } // SetHandler不支持值类型 if (Field.DeclaringType.IsValueType) { // 不相等才赋值 Object v = GetValue(obj); if (!Object.Equals(value, v)) { Field.SetValue(obj, value); } } else { SetHandler.Invoke(obj, value); } }
public override Object CreateInstance(params Object[] parameters) { if (Type.ContainsGenericParameters || Type.IsGenericTypeDefinition) { throw new XException(Type.FullName + "类是泛型定义类,缺少泛型参数!"); } if (Type.IsValueType || Type.IsArray) { return(Handler.Invoke(parameters)); } // 准备参数类型数组,以匹配构造函数 //var paramTypes = Type.EmptyTypes; //if (parameters != null && parameters.Length > 0) //{ // var list = new List<Type>(); // foreach (var item in parameters) // { // if (item != null) // list.Add(item.GetType()); // else // list.Add(typeof(Object)); // } // paramTypes = list.ToArray(); //} var paramTypes = TypeX.GetTypeArray(parameters); var ctor = GetConstructor(paramTypes); var handler = GetHandler(ctor); if (handler != null) { return(handler.Invoke(parameters)); } if (paramTypes != Type.EmptyTypes) { paramTypes = Type.EmptyTypes; ctor = GetConstructor(paramTypes); handler = GetHandler(ctor); if (handler != null) { // 更换了构造函数,要重新构造构造函数的参数 var ps = ctor.GetParameters(); parameters = new Object[ps.Length]; for (int i = 0; i < ps.Length; i++) { // 处理值类型 if (ps[i].ParameterType.IsValueType) { parameters[i] = TypeX.CreateInstance(ps[i].ParameterType); } else { parameters[i] = null; } } // 如果这里创建失败,后面还可以创建一个未初始化 try { return(handler.Invoke(parameters)); } catch { } } } // 如果没有找到构造函数,则创建一个未初始化的对象 return(FormatterServices.GetSafeUninitializedObject(Type)); }
/// <summary>获取一个类型的元素类型</summary> /// <param name="type">类型</param> /// <returns></returns> public override Type GetElementType(Type type) { return(TypeX.GetElementType(type)); }
public Type[] CreateDuckTypes(Type interfaceType, Type[] duckedTypes) { const string TYPE_PREFIX = "Duck"; String namespaceName = this.GetType().Namespace + "." + interfaceType.Name; CodeCompileUnit codeCU = new CodeCompileUnit(); CodeNamespace codeNsp = new CodeNamespace(namespaceName); codeCU.Namespaces.Add(codeNsp); //CodeTypeReference codeTRInterface = new CodeTypeReference(interfaceType); CodeTypeReference codeTRInterface = new CodeTypeReference(TypeX.Create(interfaceType).FullName); ReferenceList references = new ReferenceList(); // 遍历处理每一个需要代理的类 for (int i = 0; i < duckedTypes.Length; i++) { Type objectType = duckedTypes[i]; //CodeTypeReference codeTRObject = new CodeTypeReference(objectType); CodeTypeReference codeTRObject = new CodeTypeReference(TypeX.Create(objectType).FullName); references.AddReference(objectType); CodeTypeDeclaration codeType = new CodeTypeDeclaration(TYPE_PREFIX + i); codeNsp.Types.Add(codeType); codeType.TypeAttributes = TypeAttributes.Public; codeType.BaseTypes.Add(codeTRInterface); // 声明一个字段 CodeMemberField codeFldObj = new CodeMemberField(codeTRObject, "_obj"); codeType.Members.Add(codeFldObj); CodeFieldReferenceExpression codeFldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), codeFldObj.Name); // 创建一个构造函数 CodeConstructor codeCtor = new CodeConstructor(); codeType.Members.Add(codeCtor); codeCtor.Attributes = MemberAttributes.Public; codeCtor.Parameters.Add(new CodeParameterDeclarationExpression(codeTRObject, "obj")); codeCtor.Statements.Add( new CodeAssignStatement( codeFldRef, new CodeArgumentReferenceExpression("obj") ) ); // 创建成员 CreateMember(interfaceType, objectType, codeType, references, codeFldRef); } #region 编译 CSharpCodeProvider codeprov = new CSharpCodeProvider(); #if DEBUG { StringWriter sw = new StringWriter(); codeprov.GenerateCodeFromCompileUnit(codeCU, sw, new CodeGeneratorOptions()); string code = sw.ToString(); Console.WriteLine(code); } #endif CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateInMemory = true; compilerParams.ReferencedAssemblies.Add(interfaceType.Assembly.Location); references.SetToCompilerParameters(compilerParams); CompilerResults cres = codeprov.CompileAssemblyFromDom(compilerParams, codeCU); if (cres.Errors.Count > 0) { StringWriter sw = new StringWriter(); foreach (CompilerError err in cres.Errors) { sw.WriteLine(err.ErrorText); } throw new InvalidOperationException("编译错误: \n\n" + sw.ToString()); } Assembly assembly = cres.CompiledAssembly; Type[] res = new Type[duckedTypes.Length]; for (int i = 0; i < duckedTypes.Length; i++) { res[i] = assembly.GetType(namespaceName + "." + TYPE_PREFIX + i); } return(res); #endregion }
void CreateMember(Type interfaceType, Type duckType, CodeTypeDeclaration codeType, ReferenceList references, CodeFieldReferenceExpression codeFldRef) { CodeTypeReference codeTRInterface = new CodeTypeReference(TypeX.Create(interfaceType).FullName); //// 找到duckType里面是否有公共的_obj; //FieldInfo fiObj = duckType.GetField("_obj", BindingFlags.Public | BindingFlags.Instance); //Type innerType = fiObj != null ? fiObj.FieldType : null; CodeFieldReferenceExpression fdRef = null; #region 方法 foreach (var mi in interfaceType.GetMethods()) { // 忽略专用名字的方法,如属性的get/set,还有构造函数 if ((mi.Attributes & MethodAttributes.SpecialName) != 0) { continue; } CodeMemberMethod codeMethod = new CodeMemberMethod(); codeType.Members.Add(codeMethod); codeMethod.Name = mi.Name; codeMethod.ReturnType = new CodeTypeReference(mi.ReturnType); codeMethod.PrivateImplementationType = codeTRInterface; references.AddReference(mi.ReturnType); ParameterInfo[] parameters = mi.GetParameters(); CodeArgumentReferenceExpression[] codeArgs = new CodeArgumentReferenceExpression[parameters.Length]; int n = 0; Type[] pits = new Type[parameters.Length]; foreach (ParameterInfo parameter in parameters) { pits[n] = parameter.ParameterType; references.AddReference(parameter.ParameterType); CodeParameterDeclarationExpression codeParam = new CodeParameterDeclarationExpression(parameter.ParameterType, parameter.Name); codeMethod.Parameters.Add(codeParam); codeArgs[n++] = new CodeArgumentReferenceExpression(parameter.Name); } CodeMethodInvokeExpression codeMethodInvoke = new CodeMethodInvokeExpression(FindMember(duckType, mi, codeFldRef), mi.Name, codeArgs); if (mi.ReturnType == typeof(void)) { codeMethod.Statements.Add(codeMethodInvoke); } else { codeMethod.Statements.Add(new CodeMethodReturnStatement(codeMethodInvoke)); } } #endregion #region 属性 foreach (PropertyInfo pi in interfaceType.GetProperties()) { CodeMemberProperty property = new CodeMemberProperty(); codeType.Members.Add(property); property.Name = pi.Name; property.Type = new CodeTypeReference(pi.PropertyType); property.Attributes = MemberAttributes.Public; property.PrivateImplementationType = codeTRInterface; references.AddReference(pi.PropertyType); ParameterInfo[] parameters = pi.GetIndexParameters(); CodeArgumentReferenceExpression[] args = new CodeArgumentReferenceExpression[parameters.Length]; int n = 0; foreach (ParameterInfo parameter in parameters) { CodeParameterDeclarationExpression codeParam = new CodeParameterDeclarationExpression(parameter.ParameterType, parameter.Name); property.Parameters.Add(codeParam); references.AddReference(parameter.ParameterType); CodeArgumentReferenceExpression codeArgRef = new CodeArgumentReferenceExpression(parameter.Name); args[n++] = codeArgRef; } fdRef = FindMember(duckType, pi, codeFldRef); if (pi.CanRead) { property.HasGet = true; if (args.Length == 0) { property.GetStatements.Add( new CodeMethodReturnStatement( new CodePropertyReferenceExpression( fdRef, pi.Name ) ) ); } else { property.GetStatements.Add( new CodeMethodReturnStatement( new CodeIndexerExpression( fdRef, args ) ) ); } } if (pi.CanWrite) { property.HasSet = true; if (args.Length == 0) { property.SetStatements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression( fdRef, pi.Name ), new CodePropertySetValueReferenceExpression() ) ); } else { property.SetStatements.Add( new CodeAssignStatement( new CodeIndexerExpression( fdRef, args ), new CodePropertySetValueReferenceExpression() ) ); } } } #endregion #region 事件 foreach (EventInfo ei in interfaceType.GetEvents()) { fdRef = FindMember(duckType, ei, codeFldRef); StringBuilder sbCode = new StringBuilder(); sbCode.Append("public event " + ei.EventHandlerType.FullName + " @" + ei.Name + "{"); //sbCode.Append("add {" + codeFldObj.Name + "." + ei.Name + "+=value;}"); //sbCode.Append("remove {" + codeFldObj.Name + "." + ei.Name + "-=value;}"); if (fdRef == codeFldRef) { sbCode.Append("add {" + codeFldRef.FieldName + "." + ei.Name + "+=value;}"); sbCode.Append("remove {" + codeFldRef.FieldName + "." + ei.Name + "-=value;}"); } else { sbCode.Append("add {" + fdRef.FieldName + "." + codeFldRef.FieldName + "." + ei.Name + "+=value;}"); sbCode.Append("remove {" + fdRef.FieldName + "." + codeFldRef.FieldName + "." + ei.Name + "-=value;}"); } sbCode.Append("}"); references.AddReference(ei.EventHandlerType); codeType.Members.Add(new CodeSnippetTypeMember(sbCode.ToString())); } #endregion #region 递归基接口 Type[] ts = interfaceType.GetInterfaces(); if (ts != null && ts.Length > 0) { foreach (Type item in ts) { CreateMember(item, duckType, codeType, references, codeFldRef); } } #endregion }
public override Object CreateInstance(Type type, params Object[] parameters) { return(TypeX.CreateInstance(type, parameters)); }
/// <summary>类型转换</summary> /// <param name="value">数值</param> /// <param name="conversionType"></param> /// <returns></returns> public override Object ChangeType(Object value, Type conversionType) { return(TypeX.ChangeType(value, conversionType)); }
/// <summary></summary> public static void Test() { XTrace.WriteLine("创建类型……"); #region TypeX类型 TypeX type = TypeX.Create(typeof(FastTest)); Object obj = type.CreateInstance(); Debug.Assert(obj != null, "创建实例出错!"); obj = type.CreateInstance(123); Debug.Assert(obj != null, "创建实例出错!"); //obj = type.CreateInstance("1234"); //Debug.Assert(obj != null, "创建实例出错!"); obj = type.CreateInstance(111, "aaa"); Debug.Assert(obj != null, "创建实例出错!"); XTrace.WriteLine("创建值类型实例"); type = TypeX.Create(typeof(ConsoleKeyInfo)); obj = type.CreateInstance(); Debug.Assert(obj != null, "创建值类型实例出错!"); XTrace.WriteLine("创建数组类型实例"); type = TypeX.Create(typeof(ConsoleKeyInfo[])); obj = type.CreateInstance(5); Debug.Assert(obj != null, "创建数组类型实例出错!"); #endregion #region 构造函数 ConstructorInfoX ctr = ConstructorInfoX.Create(typeof(FastTest)); obj = ctr.CreateInstance(); Debug.Assert(obj != null, "创建实例出错!"); ctr = ConstructorInfoX.Create(typeof(FastTest), new Type[] { typeof(Int32) }); obj = ctr.CreateInstance(123); Debug.Assert(obj != null, "创建实例出错!"); ctr = ConstructorInfoX.Create(typeof(FastTest), new Type[] { typeof(Int32), typeof(String) }); obj = ctr.CreateInstance(111, "aaa"); Debug.Assert(obj != null, "创建实例出错!"); #endregion #region 字段 FieldInfoX field = FieldInfoX.Create(typeof(FastTest), "_ID"); (obj as FastTest).ID = 111; Int32 v = (Int32)field.GetValue(obj); Debug.Assert(v == 111, "字段取值出错!"); field.SetValue(obj, 888); v = (Int32)field.GetValue(obj); Debug.Assert(v == 888, "字段赋值出错!"); KeyValuePair <Int32, Int32> kv = new KeyValuePair <int, int>(123456, 222); field = FieldInfoX.Create(kv.GetType(), "Key"); //field.SetValue(kv, 123456); v = (Int32)field.GetValue(kv); Debug.Assert(v == 123456, "字段取值出错!"); field = FieldInfoX.Create(typeof(FastTest), "_Name"); field.SetValue("动态赋值"); String v2 = (String)field.GetValue(); Debug.Assert(v2 == "动态赋值", "静态字段出错!"); #endregion #region 属性 PropertyInfoX p = typeof(FastTest).GetProperty("ID"); v = (Int32)p.GetValue(obj); Debug.Assert(v == 888, "属性取值出错!"); p.SetValue(obj, 999); v = (Int32)p.GetValue(obj); Debug.Assert(v == 999, "属性赋值出错!"); p = PropertyInfoX.Create(typeof(FastTest), "Name"); field.SetValue("属性动态赋值"); v2 = (String)field.GetValue(); Debug.Assert(v2 == "属性动态赋值", "静态字段出错!"); #endregion #region 方法 MethodInfoX method = MethodInfoX.Create(typeof(FastTest), "Test2"); method.Invoke(obj); method = typeof(FastTest).GetMethod("GetFullName"); Console.WriteLine(method.Invoke(null, 123, "abc")); #endregion }
/// <summary>获取类型的友好名称</summary> /// <param name="type">指定类型</param> /// <param name="isfull">是否全名,包含命名空间</param> /// <returns></returns> public override String GetName(Type type, Boolean isfull) { return(TypeX.GetName(type, isfull)); }
public override Object CreateInstance(params Object[] parameters) { if (Type.ContainsGenericParameters || Type.IsGenericTypeDefinition) { throw new XException(Type.FullName + "类是泛型定义类,缺少泛型参数!"); } if (Type.IsValueType) { return(Handler.Invoke(parameters)); } // 数组的动态构造参数是元素个数,如果未指定,应该默认0 if (Type.IsArray) { if (parameters == null || parameters.Length < 1) { parameters = new Object[] { 0 } } ; return(Handler.Invoke(parameters)); } //// 无参数,直接构造 //if (parameters == null || parameters.Length < 1) return Handler.Invoke(new Object[0]); // 准备参数类型数组,以匹配构造函数 //var paramTypes = Type.EmptyTypes; //if (parameters != null && parameters.Length > 0) //{ // var list = new List<Type>(); // foreach (var item in parameters) // { // if (item != null) // list.Add(item.GetType()); // else // list.Add(typeof(Object)); // } // paramTypes = list.ToArray(); //} var paramTypes = TypeX.GetTypeArray(parameters); var ctor = GetConstructor(paramTypes); var handler = GetHandler(ctor); if (handler != null) { return(handler.Invoke(parameters)); } if (paramTypes != Type.EmptyTypes) { paramTypes = Type.EmptyTypes; ctor = GetConstructor(paramTypes); handler = GetHandler(ctor); if (handler != null) { // 更换了构造函数,要重新构造构造函数的参数 var ps = ctor.GetParameters(); parameters = new Object[ps.Length]; for (int i = 0; i < ps.Length; i++) { // 处理值类型 if (ps[i].ParameterType.IsValueType) { parameters[i] = TypeX.CreateInstance(ps[i].ParameterType); } else { parameters[i] = null; } } // 如果这里创建失败,后面还可以创建一个未初始化 try { return(handler.Invoke(parameters)); } catch { } } } // 如果没有找到构造函数,则创建一个未初始化的对象 return(FormatterServices.GetSafeUninitializedObject(Type)); } DictionaryCache <ConstructorInfo, FastHandler> _cache = new DictionaryCache <ConstructorInfo, FastHandler>(); FastHandler GetHandler(ConstructorInfo constructor) { if (constructor == null) { return(null); } return(_cache.GetItem(constructor, key => GetConstructorInvoker(Type, key))); } ConstructorInfo GetConstructor(Type[] paramTypes) { var bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; // 1,如果参数为null,则找第一个参数 // 2,根据参数找一次,如果参数为空,也许能找到无参构造函数 // 3,如果还没找到,参数又为空,采用第一个构造函数。这里之所以没有和第一步合并,主要是可能调用者只想要无参构造函数,而第一个不是 ConstructorInfo constructor = null; if (paramTypes == null) { constructor = Type.GetConstructors(bf).FirstOrDefault(); paramTypes = Type.EmptyTypes; } if (constructor == null) { constructor = Type.GetConstructor(bf, null, paramTypes, null); } //if (constructor == null) throw new Exception("没有找到匹配的构造函数!"); if (constructor == null && paramTypes == Type.EmptyTypes) { constructor = Type.GetConstructors(bf).FirstOrDefault(); } return(constructor); }
/// <summary>根据名称获取类型</summary> /// <param name="typeName">类型名</param> /// <param name="isLoadAssembly">是否从未加载程序集中获取类型。使用仅反射的方法检查目标类型,如果存在,则进行常规加载</param> /// <returns></returns> public override Type GetType(String typeName, Boolean isLoadAssembly) { return(TypeX.GetType(typeName, isLoadAssembly)); }