因为一个程序BUG发现的奇怪问题,以前完全不知道要这样写


如果说需要验证一个字符串是否符合一个枚举 


可以用 


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


可以得到 枚举类型 的 实例,如果不在枚举里就会报错


要验证的信息 可以是 文本,也可以是 数字

比如 

  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" 导入,都没有问题


但是TMD!!!!

如果你导入了 “3”, 这个是不在枚举,但是他不会报错,用 Enum.TryParse 也不会返回false


他会成功转换成 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();
        }
    }


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