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

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

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号