c#定义特性,通过反射获取特性

当你定义了一个特性,并将其应用到类或方法上后,你可以使用反射来获取这些特性的信息。以下是一个简单的示例,展示如何使用反射来获取类和方法的特性信息:

csharp 复制代码
using System;
using System.Reflection;

// 定义一个特性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class MyCustomAttribute : Attribute
{
    public string Description { get; set; }

    public MyCustomAttribute(string description)
    {
        Description = description;
    }
}

// 应用特性
[MyCustomAttribute("This is a class description")]
class MyClass
{
    [MyCustomAttribute("This is a method description")]
    public void MyMethod()
    {
        // 方法体
    }
}

class Program
{
    static void Main()
    {
        // 获取 MyClass 类上的特性
        Type myClassType = typeof(MyClass);
        object[] classAttributes = myClassType.GetCustomAttributes(typeof(MyCustomAttribute), false);
        
        foreach (MyCustomAttribute attribute in classAttributes)
        {
            Console.WriteLine("Class Description: " + attribute.Description);
        }

        // 获取 MyMethod 方法上的特性
        MethodInfo myMethod = myClassType.GetMethod("MyMethod");
        object[] methodAttributes = myMethod.GetCustomAttributes(typeof(MyCustomAttribute), false);

        foreach (MyCustomAttribute attribute in methodAttributes)
        {
            Console.WriteLine("Method Description: " + attribute.Description);
        }
    }
}

在上面的示例中,我们使用了反射来获取 MyClass 类和 MyMethod 方法上的特性信息。首先,我们使用 typeof 运算符获取 MyClass 类的 Type 对象,然后使用 GetCustomAttributes 方法来获取类和方法上的特性信息。

通过这样的方式,我们可以在运行时访问并读取类和方法上的特性信息,以获取它们的元数据信息。希望这个示例对你有所帮助。如果你有任何问题,请随时问我。

相关推荐
七七墨染9 小时前
DotMemory系列:5. 如何实现自动化抓取和应用自托管
运维·c#·自动化
王家羽翼-王羽10 小时前
C# 连接 PLC 的S7西门子协议读写,样例分享
c#
斯内科10 小时前
C#进行CAN【控制器局域网】通讯
c#·can·pcanbasic.net
张人玉13 小时前
C#WPF——MVVM框架编写管理系统所遇到的问题
开发语言·c#·wpf·mvvm框架
马达加斯加D13 小时前
C# --- 如何写UT
前端·c#·log4j
Charles_go13 小时前
C#中级39、什么是依赖注入设计模式
java·设计模式·c#
eggcode14 小时前
C#开源库ACadSharp将Dwg转Dxf
c#·dxf·dwg
拼好饭和她皆失14 小时前
C#学习入门
开发语言·学习·c#
小小编程能手16 小时前
大小端字节序
c#
冒泡P18 小时前
【Unity】TextMeshPro富文本中使用精灵图集
ui·unity·c#·游戏引擎