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中使用特性配置对象与数据库表的映射关系。

测试与验证:

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

安全与权限:

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

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

相关推荐
草莓熊Lotso33 分钟前
Qt 进阶核心:UI 开发 + 项目解析 + 内存管理实战(从 Hello World 到对象树)
运维·开发语言·c++·人工智能·qt·ui·智能手机
2501_9418656338 分钟前
从事件驱动到异步架构的互联网工程语法构建与多语言实践分享
java·开发语言·jvm
前端 贾公子4 小时前
v-if 与 v-for 的优先级对比
开发语言·前端·javascript
嗯嗯=5 小时前
python学习篇
开发语言·python·学习
不会c嘎嘎7 小时前
QT中的常用控件 (二)
开发语言·qt
是一个Bug7 小时前
50道核心JVM面试题
java·开发语言·面试
朱朱没烦恼yeye8 小时前
java基础学习
java·python·学习
烛阴8 小时前
C# 正则表达式(5):前瞻/后顾(Lookaround)——零宽断言做“条件校验”和“精确提取”
前端·正则表达式·c#
她和夏天一样热8 小时前
【观后感】Java线程池实现原理及其在美团业务中的实践
java·开发语言·jvm
lkbhua莱克瓦248 小时前
进阶-索引3-性能分析
开发语言·数据库·笔记·mysql·索引·性能分析