Home  >  Article  >  Backend Development  >  PropertyInfo class in C#

PropertyInfo class in C#

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2024-01-17 14:46:35819browse

C#'s PropertyInfo class is used to reflect the property information of a class, including property names, data types, access modifiers, etc. Using the PropertyInfo class, you can dynamically obtain and set property values ​​of a class at runtime.

PropertyInfo class in C#

The PropertyInfo class of C# is used to reflect the property information of a class, including property name, data type, access modifier, etc.

The following are the main members of the PropertyInfo class:

  1. Name: Gets or sets the property name.

  2. DeclaringType: Gets the type of the class that defines this attribute.

  3. PropertyType: Get the data type of the property.

  4. IsStatic: Gets a value indicating whether the property is a static property.

  5. CanRead: Gets a value indicating whether the property is readable.

  6. CanWrite: Gets a value indicating whether the property is writable.

  7. GetValue(Object): Returns the value of this property on the specified object.

  8. SetValue(Object, Object): Set the value of this property on the specified object.

Using the PropertyInfo class, you can dynamically get and set the property values ​​of a class at runtime. For example, the property value can be obtained in the following way:

PropertyInfo propertyInfo = typeof(Person).GetProperty("Name");
string name = (string)propertyInfo.GetValue(person);

The above code uses the typeof operator to obtain the Type object of the Person class, and obtains the PropertyInfo object of the Name property through the GetProperty method. Then use the GetValue method to get the Name attribute value of the person object and cast it to string type.

In addition, you can also use the SetValue method to set the attribute value, for example:

PropertyInfo propertyInfo = typeof(Person).GetProperty("Age");
propertyInfo.SetValue(person, 18);

The above code uses the GetProperty method to obtain the PropertyInfo object of the Age attribute, and uses the SetValue method to set the Age attribute value of the person object is 18.

The above is the detailed content of PropertyInfo class in C#. 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
Previous article:accumulate function in CNext article:accumulate function in C