如何获得一个类的属性列表?如何获得、属性、列表

2023-09-02 10:12:22 作者:我们、不过如此

我如何得到一个类的所有属性?

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 to GetValue To look at non-public properties, use (for example) GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) (which returns all public/private instance properties ).