利用反射访问类属性
问题: 如何获取一个类所有属性的列表?
答案: 反射提供了解决此问题的方案。对于给定的实例,可以使用以下代码:
<code class="language-csharp">obj.GetType().GetProperties();</code>
要访问与类型关联的属性,请使用:
<code class="language-csharp">typeof(Foo).GetProperties();</code>
考虑以下示例类:
<code class="language-csharp">class Foo { public int A {get;set;} public string B {get;set;} }</code>
要检索并显示其为新实例化的 Foo 对象的属性值:
<code class="language-csharp">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)); }</code>
其他注意事项:
要检索静态属性值,请将 null 作为第一个参数传递给 GetValue。
要包含非公共属性,请使用更细粒度的绑定标志,例如:
<code class="language-csharp"> GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)</code>
这将检索所有公共和私有实例属性。
以上是如何使用反射检索班级的属性?的详细内容。更多信息请关注PHP中文网其他相关文章!