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

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

相关推荐
MaoziShan1 小时前
CMU Subword Modeling | 09 Lexemes, or What Dictionaries Know about Morphology
开发语言·人工智能·机器学习·语言模型·自然语言处理·c#
游乐码1 小时前
c#选择排序
c#·排序算法
listhi5203 小时前
基于C#实现动态人脸检测
开发语言·c#
rabbitlzx6 小时前
《Async in C# 5.0》第十四章 深入探讨编译器对于async的转换
java·开发语言·c#·异步·asynchronous
智商偏低7 小时前
unity 如何渲染大场景
c#
光泽雨9 小时前
单例模式代码理解
开发语言·c#
软泡芙10 小时前
【C#】一个原始的标准蓝牙心率血氧服务的数据:字节数组byte[]有5个数据分别的0、0、240、0、240,转成IEEE 11073 SFLOAT
c#
gc_22991 天前
C#学习调用OpenMcdf模块解析ole数据的基本用法(2)
c#·ole·openmcdf·offvis软件
bugcome_com1 天前
C# 变量详解(从入门到掌握)
c#
kylezhao20191 天前
C#中如何防止序列化文件丢失和损坏
c#