Home >Backend Development >C++ >How Can I Retrieve a Class's Properties Using Reflection?
Use the reflection access class attribute
Question:
How to get a list of all attributes of a class?Answer: reflection provides a solution to this problem. For a given example, you can use the following code:
To access the attributes associated with the type, please use:
<code class="language-csharp">obj.GetType().GetProperties();</code>Consider the following example category:
<code class="language-csharp">typeof(Foo).GetProperties();</code>To retrieve and display the attribute value of the newly instant FOO object:
<code class="language-csharp">class Foo { public int A {get;set;} public string B {get;set;} }</code>Other precautions:
<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>
To retrieve the static attribute value, please pass NULL as the first parameter to getValue.
The above is the detailed content of How Can I Retrieve a Class's Properties Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!