如何从“名称”的字符串表示形式中选择枚举值?

发布于 2024-12-15 23:19:35 字数 226 浏览 3 评论 0原文

我有这样的枚举,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

记忆里有你的影子 2024-12-22 23:19:35

使用 Enum.Parse 方法从字符串中获取枚举值,然后转换为 int:

string pet = "Dog";
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet);
int petValue = (int)petType;

Use the Enum.Parse method to get the enum value from the string, then cast to int:

string pet = "Dog";
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet);
int petValue = (int)petType;
旧人哭 2024-12-22 23:19:35

其他人已经建议使用 Enum.Parse() 但要小心此方法,因为它不仅解析枚举的名称,而且还尝试匹配其值。
为了清楚起见,让我们看一个小例子:

PetType petTypeA = (PetType)Enum.Parse(typeof(PetType), "Dog");
PetType petTypeB = (PetType)Enum.Parse(typeof(PetType), "1");

两个解析调用的结果都是 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:

PetType petTypeA = (PetType)Enum.Parse(typeof(PetType), "Dog");
PetType petTypeB = (PetType)Enum.Parse(typeof(PetType), "1");

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.

甩你一脸翔 2024-12-22 23:19:35

如果您使用的是 .Net 4,则可以使用 Enum.TryParse

PetType result;
if (Enum.TryParse<PetType>(pet, out result))
    return (int)result;
else
    throw something with an error message

If you are using .Net 4 you can use Enum.TryParse

PetType result;
if (Enum.TryParse<PetType>(pet, out result))
    return (int)result;
else
    throw something with an error message
森林散布 2024-12-22 23:19:35
(PetType)Enum.Parse(typeof(PetType), pet)
(PetType)Enum.Parse(typeof(PetType), pet)
俯瞰星空 2024-12-22 23:19:35

您可以使用字符串作为参数,例如

int pet=1;
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet.ToString());

Or

string pet="Dog";
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet);

you can use a string as parameter like

int pet=1;
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet.ToString());

Or

string pet="Dog";
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文