如何获得一个类的属性列表? [英] How to get the list of properties of a class?
本文介绍了如何获得一个类的属性列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何得到一个类的所有属性?
How do I get a list of all the properties of a class?
推荐答案
反思;一个实例:
obj.GetType().GetProperties();
对于类型:
typeof(Foo).GetProperties();
例如:
class Foo {
public int A {get;set;}
public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
继反馈...
Following feedback...
- 要获取静态属性的值,通过
空
作为第一个参数的GetValue
- 要看看非公共属性,使用(例如)
的GetProperties,(BindingFlags.Public | BindingFlags.NonPublic可| BindingFlags.Instance)
(返回所有的公共/私有实例属性)。
- To get the value of static properties, pass
null
as the first argument toGetValue
- To look at non-public properties, use (for example)
GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
(which returns all public/private instance properties ).
这篇关于如何获得一个类的属性列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文