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

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

相关推荐
simonkimi1 小时前
解决无法在Cursor中使用C# Dev Kit的问题
c#·cursor
枯萎穿心攻击7 小时前
ECS由浅入深第三节:进阶?System 的行为与复杂交互模式
开发语言·unity·c#·游戏引擎
小码编匠7 小时前
WPF 自定义TextBox带水印控件,可设置圆角
后端·c#·.net
水果里面有苹果7 小时前
17-C#的socket通信TCP-1
开发语言·tcp/ip·c#
阿蒙Amon15 小时前
C# Linq to SQL:数据库编程的解决方案
数据库·c#·linq
iCxhust17 小时前
c# U盘映像生成工具
开发语言·单片机·c#
emplace_back19 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
阿蒙Amon20 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
深海潜水员21 小时前
【Behavior Tree】-- 行为树AI逻辑实现- Unity 游戏引擎实现
游戏·unity·c#