C# 在枚举中使用数字 [英] C# using numbers in an enum

查看:114
本文介绍了C# 在枚举中使用数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有效的枚举

public enum myEnum
{
  a= 1,
  b= 2,
  c= 3,
  d= 4,
  e= 5,
  f= 6,
  g= 7,
  h= 0xff
};

但这不是

public enum myEnum
{
  1a = 1,
  2a = 2,
  3a = 3,
};

有没有办法在枚举中使用数字?我已经有了可以从枚举填充下拉列表的代码,所以它会非常方便

Is there a way I can use an number in a enum? I already have code that would populate dropdowns from enums so it would be quite handy

推荐答案

C# 中根本没有标识符可以以数字开头(出于词法/解析原因).考虑向您的枚举值添加 [Description] 属性:

No identifier at all in C# may begin with a number (for lexical/parsing reasons). Consider adding a [Description] attribute to your enum values:

public enum myEnum
{
    [Description("1A")]
    OneA = 1,
    [Description("2A")]
    TwoA = 2,
    [Description("3A")]
    ThreeA = 3,
};

然后你可以像这样从枚举值中获取描述:

Then you can get the description from an enum value like this:

((DescriptionAttribute)Attribute.GetCustomAttribute(
    typeof(myEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
        .Single(x => (myEnum)x.GetValue(null) == enumValue),    
    typeof(DescriptionAttribute))).Description

根据下面 XSA 的评论,我想扩展一下如何使其更具可读性.最简单的是,您可以创建一个静态(扩展)方法:

Based on XSA's comment below, I wanted to expand on how one could make this more readable. Most simply, you could just create a static (extension) method:

public static string GetDescription(this Enum value)
{
    return ((DescriptionAttribute)Attribute.GetCustomAttribute(
        value.GetType().GetFields(BindingFlags.Public | BindingFlags.Static)
            .Single(x => x.GetValue(null).Equals(value)),
        typeof(DescriptionAttribute)))?.Description ?? value.ToString();
}

是否要使其成为扩展方法取决于您,在上面的实现中,如果没有提供 [DescriptionAttribute],我已将其回退到枚举的正常名称.

It's up to you whether you want to make it an extension method, and in the implementation above, I've made it fallback to the enum's normal name if no [DescriptionAttribute] has been provided.

现在您可以通过以下方式获取枚举值的描述​​:

Now you can get the description for an enum value via:

myEnum.OneA.GetDescription()

这篇关于C# 在枚举中使用数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆