使用Enum.Prase及Enum.TryPrase时的注意事项-创新互联

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

成都创新互联基于成都重庆香港及美国等地区分布式IDC机房数据中心构建的电信大带宽,联通大带宽,移动大带宽,多线BGP大带宽租用,是为众多客户提供专业内江机房主机托管报价,主机托管价格性价比高,为金融证券行业服务器托管,ai人工智能服务器托管提供bgp线路100M独享,G口带宽及机柜租用的专业成都idc公司。

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

可以用

(枚举类型)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是这样解释的

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

所以,上面那段代码正确的写法是

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

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

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


当前文章:使用Enum.Prase及Enum.TryPrase时的注意事项-创新互联
分享网址:http://pwwzsj.com/article/dpedci.html