利用反射訪問類屬性
問題: 如何獲取一個類所有屬性的列表?
答案: 反射提供了解決此問題的方案。對於給定的實例,可以使用以下代碼:
<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中文網其他相關文章!