Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through poco-class properties

Tags:

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

}

Is there any way to make a nested foreach that gets each container name, with an inne loop that gets each property name + value?

Hope you get the idea, otherwise ill elaborate, thanks!

like image 271
Johan Avatar asked Oct 16 '25 15:10

Johan


1 Answers

Yes, like this:

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

Live example: http://rextester.com/PNV12550

like image 102
Jamiec Avatar answered Oct 18 '25 04:10

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!