【问题标题】:How to use enum in if statement?如何在 if 语句中使用枚举?
【发布时间】:2013-04-17 11:45:28
【问题描述】:

我有 ASP.NET 应用程序,想在 if 语句中使用枚举。

我以这种方式获得变量:

string choice = (string)Session["export_choice"];
if(choice == <here goes enum>)
{
}
else
{
}

枚举只能有 2 个字符串值。

【问题讨论】:

标签: asp.net if-statement enums


【解决方案1】:

这通常是我使用switch的地方:

myEnumType myEnumChoice;

if (Enum.TryParse(choice, out myEnumChoice))
{
    switch(myEnumChoice)
    {
        case myEnumType.FirstEnum:
            //doSomething();
            break;
        case myEnumType.SecondEnum:
            //doSomethingElse();
            break;
    }
}
else
    throw new ArgumentException(string.Format("Unexpected enum value: {0}", choice));

【讨论】:

  • 我忘了写枚举选项是非英语单词。
  • 没关系 - 只需将 myEnumType 替换为您的枚举类型,然后将 FirstEnumSecondEnum 替换为您的非英语单词。
  • 好的。但是,如果这些词是西里尔文呢?
  • 如果枚举类型定义和值无效,则代码根本无法编译。
【解决方案2】:

使用

EnumChoice choice = (EnumChoice) Enum.Parse(typeof(ChumChoice), (string)Session["export_choice"] , true);

EnumChoice 是枚举类型

你可以像这样使用它

if(choice== EnumChoice.X)
{
}
else
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2016-01-04
    • 1970-01-01
    相关资源
    最近更新 更多