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

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

相关推荐
小码编匠1 小时前
WPF 自定义分页控件,可通过样式模板修改外观
后端·c#·.net
CoderPractice2 小时前
C#控制台小项目-飞行棋
开发语言·c#·小游戏·飞行棋
ajassi20003 小时前
开源 C# .net mvc 开发(八)IIS Express轻量化Web服务器的配置和使用
linux·开源·c#·mvc·.net
19H7 小时前
Flink-Source算子状态恢复分析
c#·linq
枯萎穿心攻击9 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue11 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
昏睡红猹19 小时前
C#脚本化(Roslyn):如何在运行时引入nuget包
c#
张人玉19 小时前
C# 常量与变量
java·算法·c#
就是有点傻20 小时前
在C#中,可以不实例化一个类而直接调用其静态字段
c#
软件黑马王子20 小时前
C#系统学习第八章——字符串
开发语言·学习·c#