Enum.Parse(),无疑是一个更合适的方法? [英] Enum.Parse(), surely a neater way?

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

问题描述

说我有一个枚举,

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()第一,从一个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屋!

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