如何从“名称”的字符串表示形式中选择枚举值?
我有这样的枚举,
public enum PetType
{
Dog = 1,
Cat = 2
}
我也有 string pet = "Dog"
。我如何返回1?我正在考虑的伪代码是:
select Dog_Id from PetType where PetName = pet
I have enum like this
public enum PetType
{
Dog = 1,
Cat = 2
}
I also have string pet = "Dog"
. How do I return 1? Pseudo code I'm thinking about is:
select Dog_Id from PetType where PetName = pet
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
Enum.Parse
方法从字符串中获取枚举值,然后转换为 int:Use the
Enum.Parse
method to get the enum value from the string, then cast to int:其他人已经建议使用 Enum.Parse() 但要小心此方法,因为它不仅解析枚举的名称,而且还尝试匹配其值。
为了清楚起见,让我们看一个小例子:
两个解析调用的结果都是 PetType.Dog (当然可以转换为 int)。
在大多数情况下,这种行为是可以的,但并非总是如此,并且值得记住 Enum.Parse() 方法的行为方式。
Others already suggested to use Enum.Parse() but be careful with this method, because it doesn't just parse name of the enum, but also tries to match its value.
To make it clear let's check small example:
The result of both parse calls will be PetType.Dog (which can be casted to int of course).
In most cases such behavior will be OK, but not always, and this is worth to remember how the Enum.Parse() method behaves.
如果您使用的是 .Net 4,则可以使用 Enum.TryParse
If you are using .Net 4 you can use Enum.TryParse
您可以使用字符串作为参数,例如
Or
you can use a string as parameter like
Or