如何在 case 语句中使用 C# 枚举值的字符串值?

发布于 2024-08-02 00:18:50 字数 595 浏览 1 评论 0原文

我已将 C# 枚举定义为,

public enum ORDER
{
    ...
    unknown,
    partial01,
    partial12,
    partial23,
}

并且可以将其值用作字符串,如下所示:

            string ss = ORDER.partial01.ToString();

但是,当我尝试在 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 have defined a C# enum as

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:

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(12

つ可否回来 2024-08-09 00:18:50

从 C# 6 开始,您可以使用: case nameof(SomeEnum.SomeValue):

Nameof 在编译时计算,简单地转换为与给定变量、类型或成员的(非限定)名称匹配的字符串。 当然,如果您重命名枚举选项名称,它也会随之改变。

Since C# 6, you can use: 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.

反话 2024-08-09 00:18:50

将开关中的字符串转换为枚举值。

(ORDER)Enum.Parse(typeof(ORDER), value, true);

Convert the string in your switch to an enum value.

(ORDER)Enum.Parse(typeof(ORDER), value, true);
心凉 2024-08-09 00:18:50

枚举是常量,但 .ToString() 的结果不是。 对于编译器来说,它是一个动态值。 您可能需要将 switch case 转换为一系列 if/else 语句

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

空城旧梦 2024-08-09 00:18:50

作为使用 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*如果只有一个内置的T Enum.Parse(字符串值) 和 TryParse 版本:)

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 (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 :)

泪冰清 2024-08-09 00:18:50

您将其设计为枚举是有原因的,但您并没有真正将其用作枚举。 为什么要获取枚举值并将其转换为字符串,然后在 switch 中使用,而不是简单地使用枚举?

您说您无法将其解析为枚举,因为某些值超出了枚举范围。 那么要问的问题是:“为什么?” 如果您允许未定义的值,那么拥有枚举有什么意义呢? 当您获得未定义的值时,您希望发生什么? 如果任何未定义值都是一样的,那么您可以使用默认情况。 如果不是,那么您可以包含与数字表示形式匹配的其他情况。

如果您确实返回了字符串,那么您可能不想使用枚举。 相反,您想要创建一个包含公共字符串常量的公共静态类,然后可以在 switch 中使用它。 这里的技巧是评估将以区分大小写的方式进行。

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 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?

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 any undefined 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.)

烟酒忠诚 2024-08-09 00:18:50

正如 Thorarin 所指出的,如果您的 switch 语句只能包含 enum 情况,请首先将您的 string 转换为 enum。 至少从 .Net Framework 4 开始,您可以使用 此处 并执行以下操作:

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;
}

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 here and do something like:

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;
}
二货你真萌 2024-08-09 00:18:50

枚举值是常量,但您尝试使用方法 (ORDER.partial01.ToString()) 的结果,而不是常量。

在我看来,最好的选择是将其切换为使用 if/else if/else 语句,而不是 switch。 这将允许您使用您想要的逻辑。

或者,如果将字符串切换为枚举值,则可以直接切换枚举值。 但是,您无法在一个开关中打开 enum + null + 其他字符串。

Enum values are constants, but you're trying to use the results of a method (ORDER.partial01.ToString()), not a constant.

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.

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.

痴情换悲伤 2024-08-09 00:18:50

枚举是常量,但 ToString() 是一个返回值的函数。 基于它被调用的枚举对象的实例。

这是两个语句:

ORDER.partial01.ToString()
ORDER.partial02.ToString()

调用相同的函数但返回两个不同的值,因此对函数 .ToString() 的调用本身不是一个常量值。

enums are constant but ToString() is a function returning a value. based on the instance of the enum object it's being called on.

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.

萌化 2024-08-09 00:18:50

就编译器而言,这不是一个静态值,因为它是一个函数调用:

ORDER.partial01.ToString()

因此,您不能将它用作 case 语句中的比较。 但是,您可以简单地执行此操作:

case "partial01"

这会起作用,因为枚举值和字符串是相同的。

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 "partial01"

That would work, since the enum value and the string are identical.

寂寞陪衬 2024-08-09 00:18:50

使用扩展

      public static string ToGender(this Gender enumValue)
        {
            switch (enumValue)
            {
                case Gender.Female:
                    return "Female";
                case Gender.Male:
                    return "Male";
                default:
                    return null;
            }
        }

示例

Gender.Male.ToGender();

Use Extension

      public static string ToGender(this Gender enumValue)
        {
            switch (enumValue)
            {
                case Gender.Female:
                    return "Female";
                case Gender.Male:
                    return "Male";
                default:
                    return null;
            }
        }

Example

Gender.Male.ToGender();
み青杉依旧 2024-08-09 00:18:50

你就不能直接说

case "partial01":

吗?

Couldn't you just instead say

case "partial01":

?

亣腦蒛氧 2024-08-09 00:18:50

只需定义一个全局变量即可,

static ORDER orderstr;

现在您可以在页面中的任何位置设置 orderstr 的值

public enum ORDER
{ 
    unknown,
    partial01,
    partial12,
    partial23,
}

switch (orderstr)
{
    case Order.Partial01:
        break;
    default:
        break;
}

simply you can define a global variable

static ORDER orderstr;

now you can set the value of orderstr anywhere in the page

public enum ORDER
{ 
    unknown,
    partial01,
    partial12,
    partial23,
}

switch (orderstr)
{
    case Order.Partial01:
        break;
    default:
        break;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文