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

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

相关推荐
玖玥拾2 小时前
Unity 3D 笔记(十二)Unity/C# Socket 网络笔记1
网络·unity·c#
EIP低代码平台3 小时前
EIP低代码平台 - 系统日志
低代码·c#·权限·工作流·netcore
玖玥拾3 小时前
Unity 3D 笔记(十五)Unity/C# Socket 网络笔记4
服务器·网络·unity·c#
EIP低代码平台12 小时前
EIP 低代码平台 - 角色维护
低代码·c#·权限·工作流·netcore
心平气和量大福大16 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
-银雾鸢尾-20 小时前
C#中HashTable相关方法
开发语言·c#
geovindu1 天前
CSharp: Flyweight Pattern
开发语言·后端·c#·.net·享元模式·结构型模式
吴可可1231 天前
C# CAD二次开发中如何退出窗口
c#
影寂ldy1 天前
C# WinForm 三种自定义控件 + 完全自定义重绘控件知识点
开发语言·c#
ellis19701 天前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#