使用Enum.Prase及Enum.TryPrase时的注意事项

由于一个程序BUG发现的奇怪问题,之前彻底不知道要这样写c#


若是说须要验证一个字符串是否符合一个枚举 ide


能够用 spa


(枚举类型)Enum.Parse(typeof(枚举类型),"要验证的信息"); 3d


能够获得 枚举类型 的 实例,若是不在枚举里就会报错blog


要验证的信息 能够是 文本,也能够是 数字字符串

好比 get

  enum 销售类型
    {
        A型 = 1,
        B型 = 2
    }

    class Program
    {
        static void Main(string[] args)
        {
            销售类型 a = (销售类型)Enum.Parse(typeof(销售类型), "A型");
            Console.WriteLine("{0} value is {1}", a.ToString(), (int)a);

            销售类型 b = (销售类型)Enum.Parse(typeof(销售类型), "2");
            Console.WriteLine("{0} value is {1}", b.ToString(), (int)b);

            销售类型 c = (销售类型)Enum.Parse(typeof(销售类型), "3");
            Console.WriteLine("{0} value is {1}", c.ToString(), (int)c);
            
            Console.ReadKey();
        }
    }



你能够把 "A型" 或者 "2" 导入,都没有问题string


可是TMD!!!!it

若是你导入了 “3”, 这个是不在枚举,可是他不会报错,用 Enum.TryParse 也不会返回falseio


他会成功转换成 3 给你。。。。。。。。。卧槽 


MSDN是这样解释的


wKioL1bRWZCCPpsmAAErgcxYkbo609.png

因此,上面那段代码正确的写法是

 enum 销售类型
    {
        A型 = 1,
        B型 = 2
    }

    class Program
    {
        static void Main(string[] args)
        {
            销售类型 a = (销售类型)Enum.Parse(typeof(销售类型), "A型");
            Console.WriteLine("{0} value is {1}", a.ToString(), (int)a);

            销售类型 b = (销售类型)Enum.Parse(typeof(销售类型), "2");
            Console.WriteLine("{0} value is {1}", b.ToString(), (int)b);

            销售类型 c = (销售类型)Enum.Parse(typeof(销售类型), "3");
            if (Enum.IsDefined(typeof(销售类型), c))
            {
                Console.WriteLine("{0} value is {1}", c.ToString(), (int)c);
            }
            else
            {
                Console.WriteLine("{0} is not an underlying value of the enumeration.", c.ToString());
            }

            Console.ReadKey();
        }
    }


嗯,人生从未有如此酸爽的感受......

相关文章
相关标签/搜索