如何为枚举分配字符串值并在开关中使用该值 [英] How to assign string values to enums and use that value in a switch
问题描述
基本上,一系列标题将传递到switch语句中,我需要将它们与枚举的字符串值进行比较。但是我几乎不知道如何正确地做到这一点。
此外,我也不知道这是否是最好的方法,所以如果有人有什么想法? / p>
例如:
枚举
{
医生=医生,
mr =先生,
mrs =先生
}
,然后切换我为它们分配的字符串值。
没有 枚举
,其基础类型为 string
。 基础类型可以是除 char以外的任何整数类型
。
如果要将字符串
转换为您的枚举
,那么您可能需要使用 解析
或 TryParse
方法。
字符串传入=医生;
//如果无法将字符串解析为TestEnum,则会引发异常。
TestEnum foo =(TestEnum)Enum.Parse(typeof(TestEnum),incoming,true);
//尝试将字符串解析为TestEnum而不抛出异常
TestEnum条;
if(Enum.TryParse(incoming,true,out bar))
{
//成功
}
否则
{
/ /该字符串不是TestEnum
的元素}
// ...
枚举TestEnum
{
医生,先生,太太
}
Basically a series of titles will be passed into the switch statement and I need to compare them against the string values of the enum. But I have little to no idea how to do this correctly.
Also, I don't know if this is even the best approach so if anyone has any ideas?
For example:
enum
{
doctor = "doctor",
mr = "mr",
mrs = "mrs"
}
and then switch through the string values I've assigned them.
You can't have an enum
with an underlying type of string
. The underlying type can be any integral type except char
.
If you want to translate a string
to your enum
then you'll probably need to use the Parse
or TryParse
methods.
string incoming = "doctor";
// throws an exception if the string can't be parsed as a TestEnum
TestEnum foo = (TestEnum)Enum.Parse(typeof(TestEnum), incoming, true);
// try to parse the string as a TestEnum without throwing an exception
TestEnum bar;
if (Enum.TryParse(incoming, true, out bar))
{
// success
}
else
{
// the string isn't an element of TestEnum
}
// ...
enum TestEnum
{
Doctor, Mr, Mrs
}
这篇关于如何为枚举分配字符串值并在开关中使用该值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!