/// <summary> /// GetTypeByFullString 通过类型的完全名称获取类型,regularName如"ESBasic.Filters.SourceFilter,ESBasic" /// </summary> public static Type GetTypeByRegularName(string regularName) { return(ReflectionHelper.GetType(regularName)); }
/// <summary> /// ChangeType 对System.Convert.ChangeType进行了增强,支持(0,1)到bool的转换,字符串->枚举、int->枚举、字符串->Type /// </summary> public static object ChangeType(Type targetType, object val) { #region null if (val == null) { return(null); } #endregion if (targetType.IsAssignableFrom(val.GetType())) { return(val); } #region Same Type if (targetType == val.GetType()) { return(val); } #endregion #region bool 1,0 if (targetType == typeof(bool)) { if (val.ToString() == "0") { return(false); } if (val.ToString() == "1") { return(true); } } #endregion #region Enum if (targetType.IsEnum) { int intVal = 0; bool suc = int.TryParse(val.ToString(), out intVal); if (!suc) { return(Enum.Parse(targetType, val.ToString())); } else { return(val); } } #endregion #region Type if (targetType == typeof(Type)) { return(ReflectionHelper.GetType(val.ToString())); } #endregion if (targetType == typeof(IComparable)) { return(val); } //将double赋值给数值型的DataRow的字段是可以的,但是通过反射赋值给object的非double的其它数值类型的属性,却不行 return(System.Convert.ChangeType(val, targetType)); }
/// <summary> /// CopyProperty 将source中的属性的值赋给target上同名的属性 /// 使用CopyProperty可以方便的实现拷贝构造函数 /// </summary> public static void CopyProperty(object source, object target) { ReflectionHelper.CopyProperty(source, target, null); }
/// <summary> /// SearchMethod 包括被继承的所有方法,也包括泛型方法。 /// </summary> public static MethodInfo SearchMethod(Type originType, string methodName, Type[] argTypes) { MethodInfo meth = originType.GetMethod(methodName, argTypes); if (meth != null) { return(meth); } meth = ReflectionHelper.SearchGenericMethodInType(originType, methodName, argTypes); if (meth != null) { return(meth); } //搜索基类 Type baseType = originType.BaseType; if (baseType != null) { while (baseType != typeof(object)) { MethodInfo target = baseType.GetMethod(methodName, argTypes); if (target != null) { return(target); } target = ReflectionHelper.SearchGenericMethodInType(baseType, methodName, argTypes); if (target != null) { return(target); } baseType = baseType.BaseType; } } //搜索基接口 if (originType.GetInterfaces() != null) { IList <MethodInfo> list = ReflectionHelper.GetAllMethods(originType.GetInterfaces()); foreach (MethodInfo theMethod in list) { if (theMethod.Name != methodName) { continue; } ParameterInfo[] args = theMethod.GetParameters(); if (args.Length != argTypes.Length) { continue; } bool correctArgType = true; for (int i = 0; i < args.Length; i++) { if (args[i].ParameterType != argTypes[i]) { correctArgType = false; break; } } if (correctArgType) { return(theMethod); } } } return(null); }
public static void SetProperty(object obj, string propertyName, object proValue) { ReflectionHelper.SetProperty(obj, propertyName, proValue, true); }