在C#中,使用PropertyInfo可以访问和操作类的属性。以下是使用PropertyInfo的一些基本示例:
获取属性的值:using System;using System.Reflection;class MyClass{ public int MyProperty { get; set; }}class Program{ static void Main() { MyClass obj = new MyClass(); obj.MyProperty = 10; PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty"); int value = (int)propertyInfo.GetValue(obj); Console.WriteLine(value); // 输出 10 }}设置属性的值:using System;using System.Reflection;class MyClass{ public int MyProperty { get; set; }}class Program{ static void Main() { MyClass obj = new MyClass(); PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty"); propertyInfo.SetValue(obj, 20); Console.WriteLine(obj.MyProperty); // 输出 20 }}获取属性的特性:using System;using System.Reflection;[AttributeUsage(AttributeTargets.Property)]class CustomAttribute : Attribute{ public string Description { get; } public CustomAttribute(string description) { Description = description; }}class MyClass{ [Custom("This is a custom attribute")] public int MyProperty { get; set; }}class Program{ static void Main() { PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty"); CustomAttribute customAttribute = (CustomAttribute)propertyInfo.GetCustomAttribute(typeof(CustomAttribute)); Console.WriteLine(customAttribute.Description); // 输出 "This is a custom attribute" }}通过使用PropertyInfo,您可以更灵活地访问和操作类的属性,从而实现更高级的功能和逻辑。


