【问题标题】:Retrieve value of Enum based on index - c#根据索引检索枚举的值 - c#
【发布时间】:2009-12-17 19:24:25
【问题描述】:

这是我的枚举:

public enum DocumentTypes
    {
        [EnumMember]
        TYPE_1 = 1,
        [EnumMember]
        TYPE_2 = 2,
        [EnumMember]
        TYPE_3 = 3,
        [EnumMember]
        TYPE_4 = 4,
        [EnumMember]
        TYPE_5 = 5,
        [EnumMember]
        TYPE_6 = 6,
        [EnumMember]
        TYPE_7 = 7,
        [EnumMember]
        TYPE_8 = 12

    }

如果我想获取'TYPE_8',如果我只有12个,有没有办法获取枚举值?

我试过了:

((DocumentTypes[])(Enum.GetValues(typeof(DocumentTypes))))[Convert.ToInt32("3")].ToString()

返回值'TYPE_4'

【问题讨论】:

标签: c# enums


【解决方案1】:

你可以直接施法:

int value = 12;
DocumentTypes dt = (DocumentTypes)value;

【讨论】:

  • 问题是如何获取字符串表示形式。
  • 将此作为练习 :-)
  • 这比 TO 问题的正确答案有更多的赞成票,因为如果您搜索“c# get enum by index”,谷歌首先会导致这一点:D
  • @DragonGamer 是正确的 :D 这正是我想要的!
  • 根据标题,这是正确的答案
【解决方案2】:
string str = "";
int value = 12;
if (Enum.IsDefined(typeof (DocumentTypes),value))
     str =  ((DocumentTypes) value).ToString();
else
     str = "Invalid Value";

这也将处理尝试使用的无效值,而不会引发内部异常

也可以用DocumentTypes替换字符串,即

DocumentTypes dt = DocumentTypes.Invalid; // Create an invalid enum
if (Enum.IsDefined(typeof (DocumentTypes),value))
   dt = (DocumentTypes) value;

还有一点,这里是如何将自定义字符串添加到枚举(复制自 this SO answer

Enum DocumentType
{ 
    [Description("My Document Type 1")]
    Type1 = 1,
    etc...
}

然后在某处添加扩展方法

public static string GetDescription<T>(this object enumerationValue) where T : struct
{
    Type type = enumerationValue.GetType();
    if (!type.IsEnum)
        throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");

    //Tries to find a DescriptionAttribute for a potential friendly name
    //for the enum
    MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
    if (memberInfo != null && memberInfo.Length > 0)
    {
        object[] attrs = memberInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            //Pull out the description value
            return ( (DescriptionAttribute) attrs[0] ).Description;
        }
    }
    //If we have no description attribute, just return the ToString of the enum
    return enumerationValue.ToString();
}

那么你可以使用:

DocumentType dt = DocumentType.Type1;
string str = dt.GetDescription<DocumentType>();

这将检索描述属性值。


编辑 - 更新代码

这是一个新版本的扩展方法,不需要事先知道 Enum 的类型。

public static string GetDescription(this Enum value)
{
    var type = value.GetType();

    var memInfo = type.GetMember(value.ToString());

    if (memInfo.Length > 0)
    {
        var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attrs.Length > 0)
            return ((DescriptionAttribute)attrs[0]).Description;
    }

    return value.ToString();
}

【讨论】:

  • 很棒的代码!但是如果我想知道这个值 [of (DocumentTypes) value] 当我不知道枚举是“DocumentTypes”类型时(在这种情况下,我应该使用泛型)?谢谢。
  • 谢谢!但是,我发现的最好方法是:return value.ToString("d");
【解决方案3】:

首先转换为您的枚举类型并调用 ToString():

string str = ((DocumentTypes)12).ToString();

【讨论】:

    【解决方案4】:

    试试这个:

    公共枚举 EnumTest { 枚举一, 枚举二, 枚举三, 未知 }; 公共类 EnumTestingClass{ [STA线程] 静态无效主要() { EnumTest tstEnum = EnumTest.Unknown; 对象 objTestEnum; objTestEnum = Enum.Parse(tstEnum.GetType(), "EnumThree"); if (objTestEnum 是 EnumTest) { EnumTest newTestEnum = (EnumTest)objTestEnum; Console.WriteLine("newTestEnum = {0}", newTestEnum.ToString()); } } }

    现在从示例代码中,您将看到 newTestEnum 将具有与字符串“EnumThree”等效的“EnumTest”中的值。

    希望这会有所帮助, 最好的祝福, 汤姆。

    【讨论】:

      【解决方案5】:
              public enum Projects
          {
              Hotels = 1,
              Homes = 2,
              Hotel_Home = 3
          }
      
      
      int projectId = rRoom.GetBy(x => x.RoomId == room.RoomId).FirstOrDefault().ProjectId.TryToInt32();
      Projects Project = (Projects)projectId;
      

      【讨论】:

      • 虽然此代码可能会为 OP 的问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并将这些知识应用到他们自己的代码中。在解释代码时,您也可能会以赞成票的形式从用户那里获得积极的反馈。
      • 所以首先,你定义你的枚举集,然后在你的代码上使用它!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      相关资源
      最近更新 更多