C# 使用反射从嵌套 类 中获取常量

C# Get constants from nested classes with reflection

我想从嵌套的 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";
    }
}

我能够获得所有 classes 的列表和所有 class 类型的列表,但是一旦我尝试在这些上使用 GetMember(),它 returns 没什么。

使用 GetNestedTypes() 代替 public 常量的正确 BindingFlags:

var nestedTypes = typeof(MainFoo).GetNestedTypes(BindingFlags.Public);
foreach (Type type in nestedTypes)
{
    FieldInfo[] constants = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
    // <do stuff here>
}