C#学习第18天:特性(Attributes)

什么是特性?


  • **定义:**特性是向程序中的元素(如类、方法、属性等)附加元数据的标签。这些元数据在运行时可通过反射获取。
  • **用途:**用于声明性编程,可以为程序提供额外的信息,而无需改变其逻辑。

特性的种类


规定特性

  • [Obsolete]:标记过时的代码,可以发出警告或错误。
cs 复制代码
public class OldClass
{
    [Obsolete("Use NewMethod instead.")]
    public void OldMethod() { }
}

class Program
{
    static void Main()
    {
        OldClass oc = new OldClass();
        oc.OldMethod(); // 编译器警告
    }
}
  • [Serializable]:标记类可以进行序列化。
cs 复制代码
[Serializable]
public class SerializableClass
{
    public int Id { get; set; }
    public string Name { get; set; }
}
  • [DllImport]:用于调用非托管代码。
cs 复制代码
using System.Runtime.InteropServices;

public class ExternalMethods
{
    [DllImport("user32.dll")]
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
}

class Program
{
    static void Main()
    {
        ExternalMethods.MessageBox(IntPtr.Zero, "Hello", "Title", 0);
    }
}

自定义特性

  • AttributeUsage\]指定特性可以应用的程序元素。

  • 使用反射获取类型和方法上的自定义特性。
cs 复制代码
using System;

// 定义自定义特性类
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DeveloperAttribute : Attribute
{
    public string Name { get; }
    public string Level { get; set; }

    public DeveloperAttribute(string name)
    {
        Name = name;
    }
}

// 使用自定义特性
[Developer("Alice", Level = "Senior")]
public class MyClass
{
    [Developer("Bob", Level = "Junior")]
    public void DoWork() { }
}

class Program
{
    static void Main()
    {
        Type type = typeof(MyClass);

        foreach (var attr in type.GetCustomAttributes(false))
        {
            if (attr is DeveloperAttribute developerAttr)
            {
                Console.WriteLine($"Class Developer: {developerAttr.Name}, Level: {developerAttr.Level}");
            }
        }

        foreach (var method in type.GetMethods())
        {
            foreach (var attr in method.GetCustomAttributes(false))
            {
                if (attr is DeveloperAttribute developerAttr)
                {
                    Console.WriteLine($"Method {method.Name} Developer: {developerAttr.Name}, Level: {developerAttr.Level}");
                }
            }
        }
    }
}

使用场景


代码文档:

  • 使用特性自动生成代码文档并验证约定。

框架开发:

  • 在ORM中使用特性配置对象与数据库表的映射关系。

测试与验证:

  • 指定单元测试的运行条件或行为。

安全与权限:

  • 基于特性实现访问控制或功能授权。

通过理解和使用特性,您能够更好地扩展程序的功能,使得代码更具可读性和可维护性。如果有任何问题或需要进一步探讨,请随时告诉我!

相关推荐
居然是阿宋7 分钟前
Kotlin函数体详解:表达式函数体 vs 代码块函数体——使用场景与最佳实践
java·开发语言·kotlin
小钊(求职中)10 分钟前
Java后端开发面试题(含答案)
java·开发语言·后端·面试
万岳软件开发小城14 分钟前
基于PHP+Uniapp的互联网医院源码:电子处方功能落地方案
开发语言·uni-app·php·软件开发·互联网医院系统源码·智慧医院app
程序猿多布16 分钟前
网络开发基础(游戏)之 粘包分包
网络·游戏·c#
Always_away42 分钟前
26考研|数学分析:数项级数
笔记·学习
想回家的一天43 分钟前
雪花算法生成int64,在前端js的精度问题
开发语言·前端·javascript
.又是新的一天.44 分钟前
03_JavaScript
开发语言·javascript·ecmascript
付出不多1 小时前
python函数与模块
开发语言·python
樱花穿过千岛湖1 小时前
第一章:Model Context Protocol (MCP)
网络·人工智能·python·网络协议·学习·tcp/ip
知识分享小能手1 小时前
JavaScript学习教程,从入门到精通,XMLHttpRequest 与 Ajax 请求详解(25)
开发语言·javascript·学习·ajax·前端框架·css3·html5