vendredi 23 octobre 2020

C# Get constants from nested classes with reflection

I'd like to create a List from all of the constants in the nested classes.

public struct SomePair
{
    public string Name, Value;

    public SomePair(string name, string value)
    {
        Name = name;
        Value = value;
    }
}

private static MemberInfo[] GetClasses() => typeof(MainFoo).GetMembers(BindingFlags.Public);
private static List<Type> GetClassTypes() => GetClasses().Select(c=>c.GetType()).ToList();

public static class MainFoo
{
    // The return value should contain the information about the SomeConstant's from both Errors and Foo.
    public static List<LocalizationPair> Dump()
    {
        List<SomePair> Dump = new List<SomePair>();
        var classes = GetClassTypes();
        foreach (Type cls in classes)
        {
            var constants = cls.GetFields(BindingFlags.Public); // <<< Is always empty...
            foreach (FieldInfo constant in constants)
            {
                Dump.Add(new SomePair(
                    $"{cls.Name}.{constant.Name}",
                    constant.GetValue(cls).ToString()
                    ));
            }
        }

        return Dump;
    }
    
    public static class Errors
    {
        public constant string SomeConstant = "a";
    }
    
    public static class Foo
    {
        public constant string SomeConstant = "a";
    }
}

I'm able to get a list of all classes and a list of all class-types but once I try to use GetMember() on those, it returns nothing.





Aucun commentaire:

Enregistrer un commentaire