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

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

相关推荐
傻啦嘿哟39 分钟前
如何用 Python 拆分 Word 文件:高效分割大型文档的完整指南
开发语言·c#
hoiii18739 分钟前
C# 读取 CSV/Excel 文件数据至 DataGridView
开发语言·c#·excel
xiaoshuaishuai843 分钟前
C# 实现“superpowers进化
运维·服务器·windows·c#
神仙别闹1 小时前
基于 MATLAB 实现 Word 的信息隐藏算法
c#·word·xhtml
csdn_aspnet10 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
游乐码16 小时前
c#lambad表达式
开发语言·c#
一念春风17 小时前
Qwen2.5 (AI模型 PC搭建)
人工智能·ai·c#·wpf·模型
~plus~19 小时前
C# 事件溯源与 CQRS 架构:用 EventStoreDB 打造可靠系统
开发语言·架构·c#
aq553560019 小时前
Laravel7.x重磅升级:十大新特性解析
开发语言·汇编·c#·html
唐青枫21 小时前
C#.NET Mapperly 深入解析:源生成映射、安装使用与工程化取舍
c#·.net