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

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

相关推荐
mudtools11 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫14 小时前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools1 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫2 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务2 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther2 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
阿幸软件杂货间2 天前
Office转PDF转换器v1.0.py
开发语言·pdf·c#
sali-tec2 天前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
Tiger_shl2 天前
【层面一】C#语言基础和核心语法-02(反射/委托/事件)
开发语言·c#