Home >Backend Development >C++ >How to Retrieve Attribute Name and Value for Properties using .NET Reflection?
<.> The technique of using the .NET reflection to obtain the attribute name and value
This article discusses how to use the .NET reflection mechanism to extract the name-value pair. We take a class called as an example.
Question: Book
Given a type, how to use reflection to obtain the characteristic name of each attribute and its associated value? Name
Author
Solution:
<code class="language-csharp">public class Book { [Author("AuthorName")] public string Name { get; private set; } }</code>
Use the characteristics of the reflection access attribute, please follow the steps below:
Use to obtain ainstance array, which represents all the properties of this type. traversed each
, and useto retrieve the custom characteristic array applied to the attribute.
typeof(Book).GetProperties()
PropertyInfo
Get the attribute name from the instance, and obtain the characteristic value from the recognized characteristics. PropertyInfo
The following examples realize the creation of a dictionary, which maps the name of the attribute name to its associated author name: GetCustomAttributes()
AuthorAttribute
The above is the detailed content of How to Retrieve Attribute Name and Value for Properties using .NET Reflection?. For more information, please follow other related articles on the PHP Chinese website!