How to get all constants of a class?

Asked

Viewed 223 times

4

My project has a class helper with several constants representing roles predefined.

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 method Seed (method used by the Entity Framework to update the database), I need to make certain user related to these values.

Currently, there is a method AdicionarUsuarioARole() who does all the work, and this method is called several times, in this way:

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

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

For example:

var listaConstantes = RolesHelper.GetAllConstantValues();

foreach(var constVal in listaConstantes)
{
    AdicionarUsuarioARole(user, constVal);
}
  • 2

    Can help you http://stackoverflow.com/questions/10261824/how-can-i-get-all-constants-of-a-type-by-reflection @jbueno?

  • I don’t know, write an answer there :p

  • Not even time, rs! The Gypsy already put an equal answer is in the link I posted above!

  • You cannot write a static method in your Helper class that returns this list/array of constants?

  • I can @igorventurelli But why would I do that if I can capture all constants using Reflection?

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);
    }

}

9

Using Linq is very simple:

var constantes = typeOf(RolesHelper).GetFields(BindingFlags.Public |
                                               BindingFlags.Static |
                                               BindingFlags.FlattenHierarchy)
                     .Where(fi => fi.IsLiteral && !fi.IsInitOnly)
                     .ToList();
  • 1

    Damn! I can’t even see your moves!

  • 3

    Almost the same as yours, actually :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.