如何获取类的属性列表? [英] How to get the list of properties of a class?
本文介绍了如何获取类的属性列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获得一个类的所有属性的列表?
How do I get a list of all the properties of a class?
推荐答案
Reflection;例如:
Reflection; for an instance:
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...
- 要获取静态属性的值,将
null
作为第一个参数传递给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屋!
查看全文