Enum.Parse(),肯定是一个更干净的方式? [英] Enum.Parse(), surely a neater way?

查看:91
本文介绍了Enum.Parse(),肯定是一个更干净的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个枚举,

  public enum颜色
{
红色,
蓝色
}

我可以看到解析它们的唯一方法是做:

  string color =Green; 
var col =(Colors)Enum.Parse(typeOf(Colors),color);

这将抛出一个 System.ArgumentException ,因为绿色不是颜色枚举的成员。 / p>

现在我真的很讨厌在try / catch中包装代码,没有更好的方法来做,不涉及我迭代每个颜色枚举,并与颜色进行字符串比较?

解决方案

使用 Enum.IsDefined( ) ,以保存自己不要包装在try / catch中。它将返回一个布尔值,无论输入是否是该枚举的有效成员。


Say I have an enum,

public enum Colours
{
    Red,
    Blue
}

The only way I can see of parsing them is doing something like:

string colour = "Green";
var col = (Colours)Enum.Parse(typeOf(Colours),colour);

This will throw a System.ArgumentException because "Green" is not a member of the Colours enum.

Now I really hate wrapping code in try/catch's, is there no neater way to do this that doesn't involve me iterating through each Colours enum, and doing a string comparison against colour?

解决方案

Use Enum.IsDefined() first, to save yourself from wrapping in a try/catch. It will return a boolean value of whether or not the input is a valid member of that enum.

这篇关于Enum.Parse(),肯定是一个更干净的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆