Enum.Parse(),肯定是一种更简洁的方法吗?
假设我有一个枚举,
public enum Colours
{
Red,
Blue
}
我能看到解析它们的唯一方法是执行以下操作:
string colour = "Green";
var col = (Colours)Enum.Parse(typeOf(Colours),colour);
这将抛出 System.ArgumentException 因为“Green”不是 Colours
枚举的成员。
现在我真的很讨厌将代码包装在 try/catch 中,是否没有更简洁的方法来做到这一点,而不需要我迭代每个 Colours
枚举,并与 colour
进行字符串比较代码>?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
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.我相信 4.0 有 Enum .TryParse
否则使用扩展方法:
I believe that 4.0 has Enum.TryParse
Otherwise use an extension method:
只是为了扩展 Sky 的链接到 .Net 4 Enum.TryParse<> ;,即
可以这样使用:
Just to expand on Sky's link to the .Net 4 Enum.TryParse<>, viz
This can be used as follows:
不,没有“不抛出”方法(类似于其他一些类所具有的 TryParse)。
但是,您可以轻松编写自己的代码,以便将 try-catch 逻辑(或 IsDefined 检查)封装在一个辅助方法中,这样就不会污染您的应用程序代码:
No, there's no "no-throw" method for this (a la TryParse that some other classes have).
However, you could easily write your own so as to encapsulate the try-catch logic (or the IsDefined check) in one helper method so it doesn't pollute your app code:
如果我正在解析“可信”枚举,那么我会使用 Enum.Parse()。
我所说的“可信”是指,我知道它将始终是一个有效的枚举,而不会出错......永远!
但有时“你永远不知道你会得到什么”,在这些时候,你需要使用可为空的返回值。由于 .net 不提供这种内置功能,因此您可以自行推出。这是我的秘诀:
要使用此方法,请像这样调用它:
只需将此方法添加到用于存储其他常用实用程序函数的类中即可。
If I'm parsing a "trusted" enum, then I use Enum.Parse().
By "trusted" I mean, I know it will ALWAYS be a valid enum without ever erroring... ever!
But there are times when "you never know what you're gonna get", and for those times, you need to use a nullable return value. Since .net doesn't offer this baked in, you can roll your own. Here's my recipe:
To use this method, call it like so:
Just add this method to a class you use to store your other commonly used utility functions.