实现枚举的正确转换

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);
  }

 

posted @ 2018-12-20 10:57  ac楚  Views(253)  Comments(0Edit  收藏  举报