Получить значение Enum на основе индекса - c # - PullRequest
24 голосов
/ 17 декабря 2009

Это мое перечисление:

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, есть ли способ получить значение enum?

Я пробовал это:

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

, который возвращает значение 'TYPE_4'

Ответы [ 4 ]

34 голосов
/ 17 декабря 2009

Вы можете напрямую разыграть его:

int value = 12;
DocumentTypes dt = (DocumentTypes)value;
23 голосов
/ 17 декабря 2009
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;

А что касается бонусного балла, вот как добавить пользовательскую строку в перечисление (скопировано из этого ответа SO )

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

Который получит значение атрибута Description.


Редактировать - обновленный код

Вот новая версия метода расширения, которому не нужно заранее знать тип 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();
}
6 голосов
/ 17 декабря 2009

Прежде всего приведите к вашему типу enum и вызовите ToString ():

string str = ((DocumentTypes)12).ToString();
0 голосов
/ 17 декабря 2009

Попробуйте это:

    public enum EnumTest
    {
        EnumOne,
        EnumTwo,
        EnumThree,
        Unknown
    };
    public class EnumTestingClass{
        [STAThread]
        static void Main()
        {
            EnumTest tstEnum = EnumTest.Unknown;
            object objTestEnum;
            objTestEnum = Enum.Parse(tstEnum.GetType(), "EnumThree");
            if (objTestEnum is EnumTest)
            {
                EnumTest newTestEnum = (EnumTest)objTestEnum;
                Console.WriteLine("newTestEnum = {0}", newTestEnum.ToString());
            }
        }
    }

Теперь из примера кода вы увидите, что newTestEnum будет иметь значение из «EnumTest», эквивалентное строке «EnumThree».

Надеюсь, это поможет, С наилучшими пожеланиями, Том.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...