如何列出类的所有变量 [英] How to list all Variables of Class
本文介绍了如何列出类的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法列出类的所有变量(字段)在C#中。
如果是比能有人给我一些例子如何将它们保存在列表
并可能使用匿名类型获得
( VAR)。
Is there a way to list all Variables (Fields) of a class in C#.
If yes than could someone give me some examples how to save them in a List
and get them maybe using Anonymous Types
(var).
推荐答案
您的问题不是非常清楚。这听起来像你想要的字段的值类的给定实例:
Your question isn't perfectly clear. It sounds like you want the values of the fields for a given instance of your class:
var fieldValues = foo.GetType()
.GetFields()
.Select(field => field.GetValue(foo))
.ToList();
注意 fieldValues
是列表<对象>
。在这里,富
是类的现有实例。
Note that fieldValues
is List<object>
. Here, foo
is an existing instance of your class.
如果你想公共
和非 - 公共
字段,则需要通过
If you want public
and non-public
fields, you need to change the binding flags via
var bindingFlags = BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public;
var fieldValues = foo.GetType()
.GetFields(bindingFlags)
.Select(field => field.GetValue(foo))
.ToList();
如果您只是想的名称:
var fieldNames = typeof(Foo).GetFields()
.Select(field => field.Name)
.ToList();
在这里,富
是类的名称。
这篇关于如何列出类的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文