How to loop on field names of a class

前端 未结 5 500
甜味超标
甜味超标 2021-01-03 20:54

I have got a class which contains more then 150 fields. i need the name of fields (not value) in an array.

because its very hard and not a good approach to write 150

5条回答
  •  攒了一身酷
    2021-01-03 21:30

    This work for me perfectly ExampleClass is class You need list all fields

    public void GetClassFields(Type t)
    {
        List fieldNames = new List(t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Select(x => x.Name));
        foreach (string name in fieldNames)
        {
            Console.WriteLine(name);
        }       
    }
    //Usage
    GetClassFields(typeof(ExampleClass));
    

提交回复
热议问题