Get the Enum value Description

后端 未结 3 1962
离开以前
离开以前 2020-12-18 07:10

I have my enumHelper class that contains these:

public static IList GetValues()
{
  IList list = new List();
  foreach (object val         


        
3条回答
  •  囚心锁ツ
    2020-12-18 08:01

    You should change:

    public static string Description(Enum value)
    {
      ...
    }
    

    to

    public static string Description(T value)
    {
       ...
    }
    

    so it accepts a value of the enumeration. Now here is where it gets tricky: you have a value, but attributes decorate the field which holds the value.

    You actually need to reflect over the enumeration's fields and check the value of each against the value you've been given (results should be cached for performance):

    foreach(var field in typeof(T).GetFields())
    {
        T fieldValue;
    
        try
        {
            fieldValue = (T) field.GetRawConstantValue();
        }
        catch(InvalidOperationException)
        {
            // For some reason, one of the fields returned is {Int32 value__},
            // which throws an InvalidOperationException if you try and retrieve
            // its constant value.
            //
            // I am unsure how to check for this state before
            // attempting GetRawConstantValue().
    
            continue;
        }
    
        if(fieldValue == value)
        {
            var attribute = LMIGHelper.GetAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
    
            return attribute == null ? value.ToString() : attribute.Description;
        }
    }
    

    Edit addressing the follow-up question

    The FillComboFromEnum method is missing the type parameter for the enum. Try this:

    public static void FillComboFromEnum(ComboBox Cbo, BindingList> List) where T : struct
    

    Notice I constrained the type to be a struct. It's not a full enumeration constraint, but it's closer than nothing.

提交回复
热议问题