【问题标题】:C# Get constants from nested classes with reflectionC# 使用反射从嵌套类中获取常量
【发布时间】:2020-10-23 14:35:06
【问题描述】:

我想从嵌套类中的所有常量创建一个列表。

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

我能够获得所有类的列表和所有类类型的列表,但是一旦我尝试对它们使用 GetMember(),它什么也不会返回。

【问题讨论】:

  • 我在任何地方都没有看到对GetNestedTypes 的呼叫,所以从那里开始。其次,您需要包含BindingFlags.Instance 和/或BindingFlags.Static 以获得任何结果。常量是静态成员。第三,.Select(c =&gt; c.GetType()) 将从序列中为RuntimeFieldInfoRuntimePropertyInfo 等投影Type 实例。您需要将每个项目 (c) 转换为 FieldInfoPropertyInfo 等,具体取决于它是什么,并分别获取 FieldTypePropertyType 属性。它不会是一个简单的 lambda 表达式。
  • 谢谢,解决了。我什至不知道这种方法存在。

标签: c# reflection constants


【解决方案1】:

将 GetNestedTypes() 与正确的 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>
}

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-16
  • 2013-08-04
  • 1970-01-01
相关资源
最近更新 更多