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

1949idc 2年前 (2024-09-18) 阅读数 334 #深度学习

要通过 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 属性上的所有自定义属性,并检查是否存在指定类型的自定义属性。最后,我们可以从获取到的自定义属性中提取所需的值进行处理。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业