예제 #1
0
        /// <summary>
        /// 获取枚举实例
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="member">成员名或值,范例:Enum1枚举有成员A=0,则传入"A"或"0"获取 Enum1.A</param>
        public static TEnum ToEnum <TEnum>(this string member)
        {
            string value = member.ToSafeString();

            if (string.IsNullOrWhiteSpace(value))
            {
                if (typeof(TEnum).IsGenericType)
                {
                    return(default(TEnum));
                }
                throw new ArgumentNullException(nameof(member), $"待转换枚举成员值有误");
            }
            var type = H_Common.GetType <TEnum>();

            if (!Enum.IsDefined(type, value))
            {
                throw new ArgumentException($"待转换枚举成员值 {member} 有误", nameof(member));
            }

            return((TEnum)Enum.Parse(type, value));
        }
예제 #2
0
        /// <summary>
        /// 通用泛型转换
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="input">输入值</param>
        public static T To <T>(object value)
        {
            if (value == null)
            {
                return(default(T));
            }
            if (value is string && string.IsNullOrWhiteSpace(value.ToString()))
            {
                return(default(T));
            }
            Type type     = H_Common.GetType <T>();
            var  typeName = type.Name.ToLower();

            try
            {
                if (typeName == "string")
                {
                    return((T)(object)value.ToString());
                }
                if (typeName == "guid")
                {
                    return((T)(object)new Guid(value.ToString()));
                }
                if (type.IsEnum)
                {
                    return(H_Convert.ToEnum <T>(value.ToString()));
                }
                if (value is IConvertible)
                {
                    return((T)Convert.ChangeType(value, type));
                }
                return((T)value);
            }
            catch
            {
                return(default(T));
            }
        }