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指定特性可以应用的程序元素。
  • 自定义特性继承自System.Attribute。
  • 使用反射获取类型和方法上的自定义特性。
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中使用特性配置对象与数据库表的映射关系。

测试与验证:

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

安全与权限:

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

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

相关推荐
见叶之秋6 分钟前
【C++】C++ 核心进阶(一):泛型编程基石 —— 模板初阶与 STL 体系开篇
开发语言·c++
Escalating_xu6 分钟前
【Makefile 进阶】从自动发现源文件、模式规则到目录分离与多模块递归构建
linux·开发语言
智者知已应修善业8 分钟前
C#用一个循环[等效]取出字符串中的数字
网络·c#·web·string·语言
艾莉丝努力练剑15 分钟前
【AI大模型接入SDK】Gemini模型接入知识体系
java·开发语言·网络·人工智能·网络协议·学习·http
传奇开心果编程19 分钟前
【Rust入门知识点学与练】第13课:枚举 Enum
开发语言·学习·rust
zhanghaha131424 分钟前
Python进阶教程:28_queue 队列模块 零基础超详细教程
java·开发语言·python
司小豆29 分钟前
第七课:DeepSeek Harness 服务与依赖注入
java·服务器·开发语言·github·ai编程
CSDN_RTKLIB32 分钟前
自己的溯源函数注意点
c#
A_nanda39 分钟前
C# 调用 .NET(Core)Web 服务混用:常见问题与 .NET 6~10 正确写法
c#·.net
weixin1997010801641 分钟前
[特殊字符]《闲鱼 + 淘宝 + 1688 三平台库存同源:二手ERP主数据治理与超卖防御》(附Python源码)
开发语言·python