Пример #1
0
 /// <summary>
 /// GetTypeByFullString 通过类型的完全名称获取类型,regularName如"ESBasic.Filters.SourceFilter,ESBasic"
 /// </summary>       
 public static Type GetTypeByRegularName(string regularName)
 {
     return ReflectionHelper.GetType(regularName);
 }
Пример #2
0
        /// <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);
        }