温馨提示×

如何在 C# 中使用 PropertyInfo

小樊
85
2024-07-08 16:49:15
栏目: 编程语言

在C#中,使用PropertyInfo可以访问和操作类的属性。以下是使用PropertyInfo的一些基本示例:

  1. 获取属性的值:
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
    }
}
  1. 设置属性的值:
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
    }
}
  1. 获取属性的特性:
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,您可以更灵活地访问和操作类的属性,从而实现更高级的功能和逻辑。

0