如何在 case 语句中使用 C# 枚举值的字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1273228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use the string value of a C# enum value in a case statement?
提问by peter.murray.rust
I have defined a C# enum as
我已经将 C# 枚举定义为
public enum ORDER
{
...
unknown,
partial01,
partial12,
partial23,
}
and can use its value as a string as in:
并且可以将其值用作字符串,如下所示:
string ss = ORDER.partial01.ToString();
However when I try to use it in a case statement it fails to compile:
但是,当我尝试在 case 语句中使用它时,它无法编译:
string value = ...
switch (value)
{
case null:
break;
case "s":
// OK
break;
case ORDER.partial01.ToString():
// compiler throws "a constant value is expected"
break;
...
I thought enums were constants. How do I get around this?
我认为枚举是常量。我该如何解决这个问题?
(I cannot parse the value into an enum as some of the values are outside the range)
(我无法将值解析为枚举,因为某些值超出了范围)
采纳答案by Joel Martinez
The enum is a constant, but the result of .ToString() is not. As far as the compiler is concerned, it is a dynamic value. You probably need to convert your switch case into a series of if/else statements
枚举是一个常量,但 .ToString() 的结果不是。就编译器而言,它是一个动态值。您可能需要将 switch case 转换为一系列 if/else 语句
回答by sipwiz
Convert the string in your switch to an enum value.
将 switch 中的字符串转换为枚举值。
(ORDER)Enum.Parse(typeof(ORDER), value, true);
回答by Reed Copsey
Enum values are constants, but you're trying to use the results of a method (ORDER.partial01.ToString()), not a constant.
枚举值是常量,但您尝试使用方法 (ORDER.partial01.ToString()) 的结果,而不是常量。
The best option, in my opinion, would be to just switch this around to using if/else if/else statements, instead of a switch. This would allow you to use the logic you are desiring.
在我看来,最好的选择是将其切换为使用 if/else if/else 语句,而不是 switch。这将允许您使用所需的逻辑。
Alternatively, if you switch your string into the enum value, you can switch on the enum values directly. You cannot switch on the enum + null + other strings, though, in one switch.
或者,如果将字符串切换为枚举值,则可以直接打开枚举值。但是,您不能在一个开关中打开 enum + null + 其他字符串。
回答by eWolf
Couldn't you just instead say
难道你不能只是说
case "partial01":
?
?
回答by Rune FS
enums are constant but ToString() is a function returning a value. based on the instance of the enum object it's being called on.
枚举是常量,但 ToString() 是一个返回值的函数。基于它被调用的枚举对象的实例。
That is the two statements:
那是两种说法:
ORDER.partial01.ToString()
ORDER.partial02.ToString()
calls the same function but returns two different values, so the call to the function .ToString() is in it self not a constant value.
调用相同的函数但返回两个不同的值,因此对函数 .ToString() 的调用本身不是常量值。
回答by John Fisher
This is not a static value as far as the compiler is concerned, since it is a function call:
就编译器而言,这不是静态值,因为它是一个函数调用:
ORDER.partial01.ToString()
Therefore, you can't use it as a comparison in a case statement. However, you can simply do this:
因此,您不能将其用作 case 语句中的比较。但是,您可以简单地执行以下操作:
case "partial01"
That would work, since the enum value and the string are identical.
那会起作用,因为枚举值和字符串是相同的。
回答by Thorarin
As an alternative to using if .. else
, you could convert your string to an enum
first. It would probably not make much sense if the number of options is small though:
作为使用的替代方法if .. else
,您可以将字符串转换为enum
第一个。但是,如果选项数量很少,则可能没有多大意义:
if (Enum.IsDefined(typeof(ORDER), value))
{
switch ((ORDER)Enum.Parse(typeof(ORDER), value)
{
case ORDER.partial01:
// ...
break;
case ORDER.partial12:
// etc
}
}
else
{
// Handle values not in enum here if needed
}
*sigh*if only there was a built-in T Enum.Parse<T>(string value)
, and a TryParse version :)
*叹气*如果只有一个内置的T Enum.Parse<T>(string value)
和 TryParse 版本:)
回答by Scott Dorman
You designed this as an enum for a reason, but you're not really making use of it as an enum. Why are you taking the enum value and converting it to a string to then use in the switch instead of simply using the enum?
您出于某种原因将其设计为枚举,但您并没有真正将其用作枚举。为什么要获取枚举值并将其转换为字符串然后在 switch 中使用而不是简单地使用枚举?
You said that you can't parse this in to an enum because some of the values are outside the enum range. The question to ask then is, "Why?" What is the point of having the enum if you are allowing values that aren't defined? What is it that you want to happen when you get a value that isn't defined? If it's the same thing for anyundefined value, then you can use the default case. If it's not, then you can include additional cases that match the numeric representation.
您说您无法将其解析为枚举,因为某些值超出了枚举范围。那么要问的问题是,“为什么?” 如果您允许未定义的值,那么使用枚举有什么意义?当您获得未定义的值时,您希望发生什么?如果任何未定义的值都是一样的,那么您可以使用默认情况。如果不是,那么您可以包含与数字表示匹配的其他案例。
If you really do get strings back, then you probably don't want to use an enum. Instead you want to create a public static class containing public string constants, which you can then use in your switch. The trick here is that the evaluation will be done in a case sensitive manner.
如果您确实确实取回了字符串,那么您可能不想使用枚举。相反,您想要创建一个包含公共字符串常量的公共静态类,然后您可以在交换机中使用它。这里的技巧是评估将以区分大小写的方式进行。
public static class Order
{
public const string Unknown = "Unknown";
public const string Partial01 = "Partial01";
public const string Partial12 = "Partial12";
public const string Partial23 = "Partial23";
}
string value = Order.Partial01
switch (value)
{
case Order.Partial01:
break;
default:
// Code you might want to run in case you are
// given a value that doesn't match.
break;
}
(You might also want to clean up your casing.)
(您可能还想清理外壳。)
回答by Dave Clemmer
As Thorarin indicated, if your switch
statement can contain only enum
cases, convert your string
to an enum
first. At least as of .Net framework 4, you can use the Enum.TryParse()<TEnum>
method as defined hereand do something like:
正如索拉林指出的那样,如果您的switch
陈述只能包含enum
案例,请将您的陈述转换string
为enum
第一个。至少从 .Net framework 4 开始,您可以使用此处Enum.TryParse()<TEnum>
定义的方法并执行以下操作:
ORDER orderEnum = ORDER.unknown;
Enum.TryParse<ORDER>(value, out orderEnum);
switch (orderEnum)
{
case ORDER.unknown:
// perhaps do something to deal with cases not matching
// to known enum values, based on the string value
break;
case ORDER.partial01:
case ORDER.partial12:
case ORDER.partial23:
// map value to known cases, etc.
break;
}
回答by Timo
Since C# 6, you can use: case nameof(SomeEnum.SomeValue):
从 C# 6 开始,您可以使用: case nameof(SomeEnum.SomeValue):
Nameof is evaluated at compile time, simply to a string that matches the (unqualified) name of the given variable, type, or member. Naturally, it changes right along should you ever rename the enum option name.
Nameof 在编译时被评估,只是一个与给定变量、类型或成员的(非限定)名称匹配的字符串。当然,如果您重命名枚举选项名称,它会立即更改。