實現枚舉的正確轉換
Enum.TryParse在判斷轉換的時候,如果值是整數,那么它會永遠轉換成功,這不太符合我們的期望。
開始實驗:
1、枚舉
public enum Hw_EnumPlatType { [Description("淘寶")] TaoBao = 1, [Description("天貓")] TianMao = 2, [Description("京東")] JingDong = 3, }
2、測試 ( true 和 false 是 flag 的值,a有標值說明沒轉換成功)
Hw_EnumPlatType a; var flag = Enum.TryParse("TaoBao", true, out a); //true flag = Enum.TryParse("aaa", true, out a); //false a=0 flag = Enum.TryParse(1.ToString(), true, out a);//true flag = Enum.TryParse(100.ToString(), true, out a);//true a=100 flag = Enum.IsDefined(typeof(Hw_EnumPlatType), "TaoBao"); //true flag = Enum.IsDefined(typeof(Hw_EnumPlatType), "aaa"); //false flag = Enum.IsDefined(typeof(Hw_EnumPlatType), 100); //false flag = Enum.IsDefined(typeof(Hw_EnumPlatType), 1); //true flag = Enum.IsDefined(typeof(Hw_EnumPlatType), 1.ToString()); //false
3、得出最終正確轉換
/// <summary> /// 判斷枚舉(TryParse判斷不準確) /// </summary> /// <param name="value">如果是int,不能是string類型,會被當成Name判斷</param> public static TEnum CheckEnum<TEnum>(this object value) where TEnum : struct { if (!Enum.IsDefined(typeof(TEnum), value)) { Console.WriteLine("枚舉轉換錯誤!"); } return (TEnum)Enum.Parse(typeof(TEnum), value.ToString(), true); }

浙公網安備 33010602011771號