mardi 27 octobre 2020

How to implement reflection to get an object field based on a generic enum

I think it is a rather simple issue, but I can't really get my head around reflection things. I'm looking for a way to initialize DropDownList based on enums with default value in Razor page

I have the following CustomModel class which have many enum properties:

public class CustomModel {
    public EnumA A { get; set; }
    public EnumB B { get; set; }
    // Other properties based on EnumC, EnumD, etc.
}

And the view model where I want to populate each enum:

public class CustomViewModel
{
    public CustomModel Custom { get; set; }
    
    public SelectList As { get; set; }
    public SelectList Bs { get; set; }
    // Other SelectList properties for all the different enums
    
    public CustomViewModel(CustomModel custom) // Will need to think about some dependency injection
    {
        Custom = custom;
        
        As = InitializeDropDownList<A>();
        Bs = InitializeDropDownList<B>();
        // Idem for all other enums
    }
    
    // Probably move it to an extension method
    private SelectList InitializeDropdownList<T>() where T : struct, Enum
    {
        // string value = ...
        
        new SelectList(new Descriptions<T>(), value)
    }
}

// Returns the string values corresponding to the generic enum
public class Descriptions<T> : List<string> where T : struct, Enum
{
    public Descriptions()
    {
        // Enumerates the T values
        foreach (T e in Enum.GetValues(typeof(T)))
        {
            // A bit simplified, because I actually use an other Description extension method
            Add(e.ToString());
        }
    }
}

Is there a way to get the value in the InitializeDropdownList function using generics and reflection as follows :

  • T = EnumA => value = CustomModel.A
  • T = EnumB => value = CustomModel.B
  • ...

I think I should use FieldInfo[] fields = Custom.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); and compare it to the actual name of T and then get the value of the field whih I don't know how to do. Does anyone have an idea of how to achieve it?

Thanks for any insights!





Aucun commentaire:

Enregistrer un commentaire