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

测试与验证:

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

安全与权限:

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

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

相关推荐
Code_流苏21 分钟前
C++课设:简易日历程序(支持传统节假日 + 二十四节气 + 个人纪念日管理)
开发语言·c++·stl容器·课设·期末大作业·日历程序·面向对象设计
Kookoos25 分钟前
ABP VNext 与 Neo4j:构建基于图数据库的高效关系查询
数据库·c#·.net·neo4j·abp vnext
道剑剑非道1 小时前
QT开发技术【ffmpeg + QAudioOutput】音乐播放器 完善
开发语言·qt·ffmpeg
武昌库里写JAVA1 小时前
iview Switch Tabs TabPane 使用提示Maximum call stack size exceeded堆栈溢出
java·开发语言·spring boot·学习·课程设计
张鱼小丸子_微辣1 小时前
.Net Framework 4/C# LINQ*
c#
lexiangqicheng1 小时前
JS-- for...in和for...of
开发语言·前端·javascript
我是老孙1 小时前
windows10 php报错
开发语言·php
y102121041 小时前
Python训练营打卡Day42
开发语言·javascript·ecmascript
2301_805054562 小时前
Python训练营打卡Day46(2025.6.6)
开发语言·python
一弓虽2 小时前
git 学习
git·学习