Enum.Parse(),肯定是一个更干净的方式? [英] Enum.Parse(), surely a neater way?
问题描述
说我有一个枚举,
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屋!