Enum.Parse(),无疑是一个更合适的方法? [英] Enum.Parse(), surely a neater way?
问题描述
说我有一个枚举,
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);
这将抛出一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx\">System.ArgumentException因为绿色不是颜色
枚举的成员。
This will throw a System.ArgumentException because "Green" is not a member of the Colours
enum.
现在我真的很讨厌包装code中的try / catch的,有没有更合适的方法来做到这一点,这并不涉及我度过每个颜色
枚举迭代,和做对字符串比较颜色
?
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
?
推荐答案
使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx\"><$c$c>Enum.IsDefined()$c$c>第一,从一个try / catch包裹保存自己。它将返回的输入是否是该枚举的有效成员的布尔值。
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屋!