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 方法来获取类和方法上的特性信息。

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

相关推荐
曹牧15 小时前
C#:24小时制时间
c#
唐青枫21 小时前
别急着拆服务:C#.NET 微服务架构从边界设计到实战
c#·.net
czhc11400756631 天前
从一份运行日志还原一次生产卡死:三个信号与一场“假卡死“
c#
Jazz_z1 天前
如何用 C# 读取 Word 中的表格数据
开发语言·c#
阿松爱学习1 天前
【Unity开发】FileStream 详解及用法指南
unity·c#·unity开发
淡海水1 天前
12-02-性能-数据结构性能调查案例1-5
数据结构·性能优化·c#
Java的搬运工1 天前
使用 C# 轻松管理 PDF 文件的用户权限
c#·用户权限
Neil20132 天前
ajax跨域请求
c#
唐青枫2 天前
别把 Razor 当成几段 HTML:C#.NET Razor Pages、MVC 视图与实战详解
c#·.net
专注仿真2 天前
CMO模型文档-活动单元基类
c#·模型·cmo·活动单元基类