如何在类的字段名称上循环 [英] How to loop on field names of a class

查看:97
本文介绍了如何在类的字段名称上循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含150多个字段的类.我需要数组中的字段名称(而不是值).

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

因为很难在代码中手动写出150个字段名(可以根据需求的变化递增或递减),所以不是很好的方法.

because its very hard and not a good approach to write 150 fields name (which can be incremented or decremented in count according to requirement change) manually in code.

我需要帮助来遍历字段名称或获取数组中的字段名称列表,以便我可以遍历它并在代码中使用它. 我正在使用Visual Studio 2008

i need help to get loop through names for field or get list of field names in a array so that i can loop over it and use it in code. i am using visual studio 2008

谢谢

推荐答案

用于所有公共+非公共实例字段:

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

或在VS2005中(评论):

or in VS2005 (comments):

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

这篇关于如何在类的字段名称上循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆