简体   繁体   English

从静态类中的静态类中获取带反射的所有字段

[英]Get all fields from static classes inside static class with reflection

I have a static class that contains a lot of static classes. 我有一个包含很多静态类的静态类。 Each inner static class contains fields. 每个内部静态类都包含字段。 I want to get all fields of all inner static classes. 我想得到所有内部静态类的所有字段。

public static class MyClass
{
    public static class MyInnerClass1
    {
        public const string Field1 = "abc";
        public const string Field2 = "def";
        public const string Field3 = "ghi";
    }
    public static class MyInnerClass2
    {
        public const int Field1 = 1;
        public const int Field2 = 2;
        public const int Field3 = 3;
    }
    ...
}

I would like to print out the name of each inner class followed by the name and value of each field. 我想打印出每个内部类的名称,后跟每个字段的名称和值。

For example: 例如:

MyInnerClass MyInnerClass

Field1 = "abc" Field1 =“abc”

... ...

I have no problem with getting the name of all the classes: 获取所有类的名称没有问题:

var members = typeof(MyClass).GetMembers(BindingFlags.Public | BindingFlags.Static);

var str = ""; 
foreach (var member in members)
{
    str += member.Name +" ";             
}

Or the name and value of all fields in a specific class: 或者特定类中所有字段的名称和值:

var fields = typeof(MyClass.MyInnerClass1).GetFields();
foreach (var field in fields)
{
    str += field.Name + "-";
    str += field.GetValue(typeof(MyClass.MyInnerClass1));
}

But how do I combine this? 但是我如何结合这个呢? The names and the number of inner static classes may change. 内部静态类的名称和数量可能会发生变化。

Try the following 请尝试以下方法

var builder = new StringBuilder();
foreach (var type in typeof(MyClass).GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))
{
  if (!type.IsAbstract)
  {
     continue;
  }

  builder.AppendLine(type.Name);
  foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)) {
     var msg = String.Format("{0} = {1}", field.Name, field.GetValue(null));
     builder.AppendLine(msg);
  }
}

string output = builder.ToString();

The use of !type.IsAbstract is done to weed on non-static nested types. 使用!type.IsAbstract来处理非静态嵌套类型。 A static type in C# is generated as abstract under the hood. C#中的静态类型在引擎盖下生成为abstract

Also my solution will pick up both public and non-public members (both types and fields). 此外,我的解决方案将选择public和非公共成员(包括类型和字段)。 I'm not sure if this was your intent or not so you may want to modify that part of my solution. 我不确定这是不是你的意图,所以你可能想要修改我的解决方案的那一部分。

You need to recursively loop through type.GetNestedTypes() : 您需要以递归方式遍历type.GetNestedTypes()

IEnumerable<FieldInfo> GetAllFields(Type type) {
    return type.GetNestedTypes().SelectMany(GetAllFields)
               .Concat(type.GetFields());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM