循环通过poco级属性

时间:2012-04-27 07:58:06

标签: c#

public partial class Foo
{
    public struct ContainerOne
    {
        public const long Sub1 = 1;
        public const long Sub2 = 2;
    }

    public struct ContainerTwo
    {
        public const long Sub3 = 3;
        public const long Sub4 = 4;
    }

}

有没有办法制作一个获取每个容器名称的嵌套foreach,并使用inne循环获取每个属性名称+值?

希望你能得到这个想法,否则就会精心制作,谢谢!

1 个答案:

答案 0 :(得分:5)

是的,就像这样:

var fooType = typeof(Foo);
foreach(var type in fooType.GetNestedTypes())
{
    Console.WriteLine(type.Name);
    foreach(var field in type.GetFields())
    {
        Console.WriteLine("{0} = {1}",field.Name,field.GetValue(null));
    }
}

实例:http://rextester.com/PNV12550