C# Attribute 介绍

C# 中的 Attribute (特性)

Attribute 是 C# 中用于向代码元素(类、方法、属性、字段、事件等)附加元数据信息的机制。Attribute 不会直接影响代码的执行逻辑,但可以用于标记信息,并在运行时或编译时通过反射进行查询和处理。它们常被用于:

  • 控制序列化行为
  • 指定数据库映射信息
  • 提供文档注释
  • 控制程序元数据

Attribute 的基本结构

所有的特性类都继承自 System.Attribute,并且可以应用于代码元素中。特性可以通过 [AttributeName] 的方式使用。

Attribute 的创建与使用

1. 创建自定义 Attribute

要创建一个自定义的 Attribute,您需要继承自 System.Attribute 并添加构造函数及属性。可以通过 [AttributeUsage] 来指定特性的适用范围。

csharp 复制代码
using System;

// 定义自定义特性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class DeveloperInfoAttribute : Attribute
{
    public string DeveloperName { get; }
    public string Project { get; set; }
    public string DateAssigned { get; set; }

    // 构造函数
    public DeveloperInfoAttribute(string developerName)
    {
        DeveloperName = developerName;
    }
}
2. 应用自定义 Attribute

接下来可以在类或方法上应用这个自定义的 DeveloperInfo 特性:

csharp 复制代码
[DeveloperInfo("Alice", Project = "CRM System", DateAssigned = "2023-01-10")]
[DeveloperInfo("Bob", Project = "ERP System", DateAssigned = "2023-05-20")]
public class SampleClass
{
    [DeveloperInfo("Charlie", Project = "Mobile App", DateAssigned = "2024-02-15")]
    public void SampleMethod()
    {
        Console.WriteLine("This is a sample method.");
    }
}
3. 通过反射读取 Attribute 信息

可以使用反射来读取代码中的特性信息:

csharp 复制代码
using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        // 获取类上的特性
        Type type = typeof(SampleClass);
        object[] classAttributes = type.GetCustomAttributes(typeof(DeveloperInfoAttribute), false);

        foreach (DeveloperInfoAttribute attr in classAttributes)
        {
            Console.WriteLine($"Class Developer: {attr.DeveloperName}, Project: {attr.Project}, Date Assigned: {attr.DateAssigned}");
        }

        // 获取方法上的特性
        MethodInfo methodInfo = type.GetMethod("SampleMethod");
        object[] methodAttributes = methodInfo.GetCustomAttributes(typeof(DeveloperInfoAttribute), false);

        foreach (DeveloperInfoAttribute attr in methodAttributes)
        {
            Console.WriteLine($"Method Developer: {attr.DeveloperName}, Project: {attr.Project}, Date Assigned: {attr.DateAssigned}");
        }
    }
}

运行结果

csharp 复制代码
Class Developer: Alice, Project: CRM System, Date Assigned: 2023-01-10
Class Developer: Bob, Project: ERP System, Date Assigned: 2023-05-20
Method Developer: Charlie, Project: Mobile App, Date Assigned: 2024-02-15

常用内置 Attribute

  • [Obsolete]: 标记某个方法或类已经过时,可以指定警告或错误。
  • [Serializable]: 标记类可以被序列化。
  • [DllImport]: 用于调用外部的非托管代码(P/Invoke)。
  • [Conditional]: 指示某个方法的执行受条件编译符的控制。
示例:[Obsolete]
csharp 复制代码
public class MyClass
{
    [Obsolete("Use NewMethod instead.")]
    public void OldMethod()
    {
        Console.WriteLine("Old method");
    }

    public void NewMethod()
    {
        Console.WriteLine("New method");
    }
}

当调用 OldMethod 时,编译器会发出警告:

csharp 复制代码
MyClass obj = new MyClass();
obj.OldMethod();  // 警告:'OldMethod' is obsolete: 'Use NewMethod instead.'

Attribute 的参数

特性的构造函数参数可以是以下几种类型:

  • 基本类型:如 int, string, bool, char 等。
  • 枚举类型。
  • Type 类型。
  • object,可以允许 null
  • 一维数组(基本类型、枚举或 Type)。

Attribute 的高级用法

  1. 允许多次使用的特性 通过 AttributeUsage 设置 AllowMultiple = true,可以让特性在同一个代码元素上多次使用。
  2. 继承和覆盖特性 子类可以继承父类的特性,且特性可以设置是否支持继承。

总结

Attribute 是 C# 中一种强大的元数据机制,允许开发者在编译时和运行时动态地控制代码行为。通过特性,您可以轻松地向代码添加元数据,并通过反射进行处理。

相关推荐
Acrelhuang6 分钟前
8.3MW屋顶光伏+光储协同:上海汽车变速器低碳工厂的能源革命-安科瑞黄安南
大数据·数据库·人工智能·物联网·数据库开发
weixin_3077791331 分钟前
判断HiveQL语句为建表语句的识别函数
开发语言·数据仓库·hive·c#
崖山数据库系统YashanDB33 分钟前
YashanDB json语法
数据库
陈三一36 分钟前
关于多数据源下Spring声明式事务管理失效问题的分析与解决
数据库·spring
我是苏苏41 分钟前
C#高级:利用LINQ进行实体列表的集合运算
c#·linq
我有医保我先冲1 小时前
SQL复杂查询与性能优化全攻略
数据库·sql·性能优化
老友@1 小时前
Kafka 全面解析
服务器·分布式·后端·kafka
烧瓶里的西瓜皮1 小时前
Go语言从零构建SQL数据库引擎(2)
数据库·sql·golang
SelectDB2 小时前
拉卡拉 x Apache Doris:统一金融场景 OLAP 引擎,查询提速 15 倍,资源直降 52%
大数据·数据库·数据分析
爱的叹息2 小时前
华为高斯(GaussDB) 集中式数据库 的开发技术手册,涵盖核心功能、开发流程、优化技巧及常见问题解决方案
数据库·gaussdb