How to get all the constants of a class?

4

My project has a helper class with multiple constants representing pre-defined roles .

public static class RolesHelper
{
    public const string ModuloUsuarios = "Usuarios";
    public const string ModuloMenus = "Menus";
    public const string ModuloBanners = "Banners";
    public const string ModuloGaleriaFotos = "GaleriasFotos";
    public const string ModuloProgramacao = "Programacao";
    public const string ModuloMetaTags = "MetaTags";
    public const string ModuloNoticias = "Noticias";
    public const string ModuloPaginas = "Paginas";
}

In the Seed method (method used by the Entity Framework to update the database), I need to make a given user to be related to these values.

Currently there is a AdicionarUsuarioARole() method that does the whole work, and this method is called several times, like this:

AdicionarUsuarioARole(user, RolesHelper.ModuloUsuarios);
AdicionarUsuarioARole(user, RolesHelper.ModuloMenus);
//E assim por diante

What I want is to get all public constants of this class in a collection, to iterate it and call the AdicionarUsuarioARole() method with each value in this collection. This way, I do not have to worry about updating the Seed method whenever I add a constant in this class.

For example:

var listaConstantes = RolesHelper.GetAllConstantValues();

foreach(var constVal in listaConstantes)
{
    AdicionarUsuarioARole(user, constVal);
}
    
asked by anonymous 07.02.2017 / 18:37

2 answers

10
// Lista todos os campos públicos e estáticos, 
// tanto da classe quanto das classes-base

foreach (var prop in typeof(SuaClasse)
                     .GetFields(BindingFlags.Public | 
                                BindingFlags.Static | 
                                BindingFlags.FlattenHierarchy))
{
    // IsLiteral determina que o valor foi criado em tempo de compilação,
    //    e não pode ser alterado.
    // IsInitOnly determina que o valor pode ser alterado no corpo do
    //    construtor.
    if(prop.IsLiteral && !prop.IsInitOnly) 
    {
        // Valor do campo
        var valor = prop.GetValue(null);
    }

}
    
07.02.2017 / 18:41
9

Using Linq is very simple:

var constantes = typeOf(RolesHelper).GetFields(BindingFlags.Public |
                                               BindingFlags.Static |
                                               BindingFlags.FlattenHierarchy)
                     .Where(fi => fi.IsLiteral && !fi.IsInitOnly)
                     .ToList();
    
07.02.2017 / 18:41