Home >Backend Development >C++ >How Can I Retrieve a Class's Properties Using Reflection?

How Can I Retrieve a Class's Properties Using Reflection?

Barbara Streisand
Barbara StreisandOriginal
2025-02-01 07:56:08111browse

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.

  • To include non -public attributes, please use a thinner granular binding logo, for example:

  • This will retrieve all public and private instance attributes.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn