2015-05-13 3 views
-4
public enum States 
{ 
     [Description("New Hampshire")] 
     NewHampshire = 29, 
     [Description("New York")] 
     NewYork = 32, 
} 

Здесь я должен получить данные по Описание Например: мне нужно 29 по «New Hampshire» Динамически не используя позицию индексаКак получить Enum значение By Описание

+2

и что вы пробовали? – null

+1

Извините, я не пробовал –

ответ

0

это способ, которым Вы можете :

States s; 
var type = typeof(States); 
foreach (var field in type.GetFields()) 
{ 
    var attribute = Attribute.GetCustomAttribute(field, 
     typeof(DescriptionAttribute)) as DescriptionAttribute; 
    if (attribute != null) 
    { 
     if (attribute.Description == "description") 
     { 
      s = (States)field.GetValue(null); 
      break; 
     } 
    } 
    else 
    { 
     if (field.Name == "description") 
     { 
      s = (Rule)field.GetValue(null); 
      break; 
     } 
    } 
} 
+0

за ваш ответ –

0

Здесь общий метод, который можно использовать с любым атрибутом

public static class Extensions 
{ 
    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) 
      where TAttribute : Attribute 
    { 
     return enumValue.GetType() 
         .GetMember(enumValue.ToString()) 
         .First() 
         .GetCustomAttribute<TAttribute>(); 
    } 
} 

Это поможет вам достичь того, что вы пытаетесь ...

+0

благодарностей за ваш ответ –

0

Вы можете передать свою строку методу GetDataByDescription. Я использовал ответ Aydin Adn для метода GetAttribute.

internal class Program 
{ 
    private static void Main(string[] args) 
    { 
     Console.WriteLine(GetDataByDescription("New Hampshire")); 
    } 

    private static int GetDataByDescription(string s) 
    { 
     foreach (States state in Enum.GetValues(typeof (States))) 
     { 
      if (GetAttribute<DescriptionAttribute>(state).Description == s) 
      { 
       return (int) state; 
      } 
     } 

     throw new ArgumentException("no such state"); 
    } 

    private static TAttribute GetAttribute<TAttribute>(Enum enumValue) 
     where TAttribute : Attribute 
    { 
     return enumValue.GetType() 
      .GetMember(enumValue.ToString()) 
      .First() 
      .GetCustomAttribute<TAttribute>(); 
    } 
} 
+0

благодаря вашему отзыву –

Смежные вопросы