如何通过 PropertyInfo获取自定义属性

653
2024/7/29 16:59:16
栏目: 深度学习
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要通过 PropertyInfo 获取自定义属性,首先需要使用 GetCustomAttributes 方法来检索属性上的所有自定义属性。以下是一个示例代码:

using System;
using System.Reflection;

class MyClass
{
    [MyCustom("Custom Attribute Value")]
    public string MyProperty { get; set; }
}

class Program
{
    static void Main()
    {
        PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty");
        object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(MyCustom), false);

        if (customAttributes.Length > 0)
        {
            MyCustom myCustomAttribute = (MyCustom)customAttributes[0];
            Console.WriteLine("Custom Attribute Value: " + myCustomAttribute.Value);
        }
    }
}

[AttributeUsage(AttributeTargets.Property)]
public class MyCustom : Attribute
{
    public string Value { get; }

    public MyCustom(string value)
    {
        Value = value;
    }
}

在上面的示例中,我们定义了一个名为 MyCustom 的自定义属性,并将其应用于 MyClass 类的 MyProperty 属性。然后,通过使用 GetCustomAttributes 方法,我们可以获取 MyProperty 属性上的所有自定义属性,并检查是否存在指定类型的自定义属性。最后,我们可以从获取到的自定义属性中提取所需的值进行处理。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: PropertyInfo的 GetValue 方法怎么用