Esempio n. 1
0
        internal static object GetValue(object value, Type type)
        {
            Type underlyingType = type;

            if (value != null && ReflectionUtils.IsPrimitiveType(type, out underlyingType))
            {
                return(ReflectionUtils.ChangeType(value, underlyingType)); // 字符串转Int32报错
            }
            else if (value != null &&
                     underlyingType.IsEnum && !value.GetType().IsEnum) // 整数或short等转成 Nullable<enum> 或 enum
            {
                return(Enum.ToObject(underlyingType, value));
            }
            else if (value == null && underlyingType.IsSubclassOf(typeof(ValueType)))
            {
                return(GetDefaultValue(type)); // null转成ulong
            }
            else // 只能强转,可能出错
            {
                return(value);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 取指定的值,找不到则返回默认值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public T Get <T>(string key, T defaultValue)
        {
            try
            {
                object value;
                if (this.TryGetValue(key, out value))
                {
                    Type type           = typeof(T);
                    Type underlyingType = type;
                    if (value == DBNull.Value)
                    {
                        return(defaultValue);
                    }
                    else if (value != null && ReflectionUtils.IsPrimitiveType(type, out underlyingType))
                    {
                        return((T)ReflectionUtils.ChangeType(value, underlyingType));
                    }
                    else if (value != null && underlyingType != type &&
                             underlyingType.IsEnum && !value.GetType().IsEnum) // 整数转成 Nullable<enum>
                    {
                        return((T)Enum.ToObject(underlyingType, value));
                    }
                    else if (value == null && underlyingType.IsSubclassOf(typeof(ValueType)))
                    {
                        return(defaultValue); // null转成ulong
                    }
                    else // 只能强转,可能出错
                    {
                        return((T)value);
                    }
                }
            }
            catch (Exception)
            {
                // 吃掉异常,by zq 2014-12-19 解决空字符串或非数值类型转ulong、转int、转uint都会抛出异常
            }

            return(defaultValue); // 返回默认值
        }