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
Release: 2025-02-01 07:56:08
Original
110 people have browsed it

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>
Copy after login
Consider the following example category:

<code class="language-csharp">typeof(Foo).GetProperties();</code>
Copy after login
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>
Copy after login
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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template