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

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

相关推荐
SunnyDays101110 小时前
使用 C# 将 Excel 转换为 Markdown 表格(含单文件与批量转换)
c#·excel转markdown
wuk99810 小时前
C# Winform实现拼图游戏
windows·microsoft·c#
唐青枫10 小时前
深入理解 System.Lazy<T>:C#.NET 延迟初始化与线程安全
c#·.net
世洋Blog1 天前
AStar算法基础学习总结
算法·面试·c#·astar·寻路
能量鸣新1 天前
资源分享第三天
c语言·开发语言·c++·python·计算机视觉·c#
剑之所向1 天前
C# Modbus 从机探测:核心报文 + 极简实现
开发语言·c#
马达加斯加D1 天前
C# --- Stream
服务器·c#·php
c#上位机1 天前
Winform开发中Label控件居中显示
c#·winform
心本无晴.1 天前
RAG技术详解:从原理到实战应用
开发语言·c#
月巴月巴白勺合鸟月半1 天前
用AI生成一个简单的视频剪辑工具 的后续 的后续
c#