【问题标题】:Enum to string value or make use of enum in if condition枚举到字符串值或在 if 条件下使用枚举
【发布时间】:2019-06-04 22:48:40
【问题描述】:

我有一个具有多个值的枚举(我在枚举内只保留了一个值)。我正在从 UI 传递这个字符串“在线系统”。有没有办法可以利用这个枚举来做条件而不是像下面这样硬编码。

if( types.type == "Online System" )

  public enum Type
        {
            [EnumMember]
            Windows
            ,[EnumMember]
            OnlineSystem
        }

更新

另外,当我将枚举值编号为 Windows = 1,OnlineSystem = 2 时,会有什么问题吗?这段代码已经存在,但我是这样编号的,这会对可能已经使用它而不编号的代码产生任何副作用吗?

【问题讨论】:

  • types.type 的数据类型是什么?它是枚举还是字符串?
  • @er-mfahhgk:显然它是一个字符串,这就是我将字符串值放在引号中的原因
  • @Learner,我在下面添加了我的答案,您需要传递字符串值,例如OnlineSystem
  • @Learner,检查一下 => stackoverflow.com/questions/4367723/…

标签: c# asp.net .net c#-4.0 enums


【解决方案1】:

首先你可以用描述属性来装饰你的枚举

  public enum Type
  {
    [Description("Windows")]
    Windows,
    [Description("Online System")]
    OnlineSystem
  }

然后您可以编写一个方法来使用反射来获取给定枚举值(要比较的值)的描述。

public static string GetEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

这将使您能够检查

var type = "Online System";
if(  type == GetEnumDescription(Type.OnlineSystem))
{
}

【讨论】:

  • 阿努,非常感谢,只是一个简单的问题,GetEnumDescription 的参数不应该以“this”关键字开头吗?
  • @Learner 'this' 关键字与扩展方法相关联。示例中的方法不是扩展方法,这就是缺少它的原因。你可以在这里阅读更多关于扩展方法的信息docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-02
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多