How to loop on field names of a class

前端 未结 5 504
甜味超标
甜味超标 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:33

    for all public + nonpublic instance fields:

    var fields = typeof(YourType).GetFields(
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    var names = Array.ConvertAll(fields, field => field.Name);
    

    or in VS2005 (comments):

    FieldInfo[] fields = typeof(YourType).GetFields(
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    string[] names = Array.ConvertAll(fields,
        delegate(FieldInfo field) { return field.Name; });
    

提交回复
热议问题