温馨提示×

C#中属性PropertyInfo怎么使用

c#
小亿
114
2024-01-19 01:38:05
栏目: 编程语言

在C#中,PropertyInfo是一个用于获取和设置属性的类。可以使用以下方式来使用PropertyInfo:

  1. 获取属性的Type: 可以使用PropertyInfo的PropertyType属性来获取属性的类型。例如,如果有一个名为"Name"的属性,可以使用以下代码获取属性的类型:
PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");
Type propertyType = propertyInfo.PropertyType;
  1. 获取属性的值: 可以使用PropertyInfo的GetValue方法来获取属性的值。需要提供一个对象实例作为参数,表示从该对象中获取属性的值。例如:
ExampleClass example = new ExampleClass();
example.Name = "John";

PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");
object propertyValue = propertyInfo.GetValue(example);
  1. 设置属性的值: 可以使用PropertyInfo的SetValue方法来设置属性的值。需要提供一个对象实例和要设置的值作为参数。例如:
ExampleClass example = new ExampleClass();

PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");
propertyInfo.SetValue(example, "John");

这些是PropertyInfo的一些基本用法。还可以使用其他方法和属性来进行更高级的操作,例如获取和设置属性的访问修饰符、属性的特性等。

0