mardi 8 janvier 2019

How to get Enum display name attribute by FieldInfo

Currently I'm working on an interesting structure of hardcoded data. Plese don't answer like create a table for this. For sure then I would give it to myself, but my curiosity is too big :).

This is main enum with which I'm creating dropdown

public enum ImportParamTypeEnum
{
    [Display(Name = "none")]
    None = 0,
    [Display(Name = "Produkty")]
    Product = 1,
    [Display(Name = "Test")]
    Test = 2,
}

Enums below are system params for above choise. For example if I selected ImportParamTypeEnum.Product in dropdown then I on the view shows up MappingColums.Product system params

public class MappingColums
{
    public enum Product
    {
        [Display(Name = "pc")]
        Token = 0,
        [Display(Name = "Nazwa")]
        Name = 1,
        [Display(Name = "Cena")]
        Price = 3,
        [Display(Name = "Ilość")]
        Quantity = 4,
        [Display(Name = "Opis")]
        Description = 5,
    }

    public enum Test
    {
        [Display(Name = "tc")]
        TokenTest = 0,
        [Display(Name = "NazwaTest")]
        NameTest = 1,
        [Display(Name = "CenaTest")]
        PriceTest = 3,
        [Display(Name = "IlośćTest")]
        QuantityTest = 4,
        [Display(Name = "OpisTest")]
        DescriptionTest = 5,
    }
}

The code below is a piece of code that creating ViewModel (I cut some stuff for simplicity):

foreach (var e in Enum.GetValues(typeof(ImportParamTypeEnum)))
{
    Type[] mappingColumnsTypes = typeof(MappingColums).GetNestedTypes();
    Type type = mappingColumnsTypes.AsEnumerable().Where(x => x.Name == e.ToString()).FirstOrDefault();
    FieldInfo[] fields = AssemblyHelper.GetFields(type);

    foreach (var f in fields)
    {
        string i = f.GetValue(null).ToString();  
    }
}

AssemblyHelper

public static FieldInfo[] GetFields(Type obj)
{
    return obj.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
}

This code work great, but I dont want to work by Values of Enum but on Display name attribute.

Question

How can I get Display name attribute by FieldInfo inside foreach (var f in fields)

Thanks!





Aucun commentaire:

Enregistrer un commentaire