PropertyInfo

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

小樊
84
2024-07-08 16:59:16
栏目: 深度学习

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

0
看了该问题的人还看了