自定义特性通过继承System.Attribute创建,使用AttributeUsage指定应用目标,如[AttributeUsage(AttributeTargets.Method)]public class LogActionAttribute : Attribute{ public string ActionName { get; set; } public LogActionAttribute(string actionName) { ActionName = actionName; }},然后可将[LogAction("用户登录", ActionName = "Authentication")]应用于方法,并通过反射在运行时读取特性数据,实现声明式编程,常用于日志、权限、序列化等场景。

特性(Attribute)是 C# 中一种为代码元素添加元数据的机制。它允许你在类、方法、属性、参数等程序元素上附加声明性信息,这些信息可以在编译时或运行时通过反射读取和处理。
例如,内置特性 [Obsolete] 可以标记某个方法已过时,编译器会给出警告:
[Obsolete("此方法已废弃,请使用 NewMethod")] void OldMethod() { }自定义特性是一个继承自 System.Attribute 的类。通常命名以 "Attribute" 结尾,但在使用时可以省略该后缀。
下面是一个简单的自定义特性的定义:
[AttributeUsage(AttributeTargets.Method)] // 限制只能用于方法 public class LogActionAttribute : Attribute { public string ActionName { get; set; }public LogActionAttribute(string actionName)
{
ActionName = actionName;
}}
说明:
定义好特性后,就可以将其应用到目标代码元素上。
class Program { [LogAction("用户登录", ActionName = "Authentication")] public static void Login() { Console.WriteLine("执行登录操作"); } }
上面代码中,[LogAction("用户登录")] 将特性附加到 Login 方法上,其中 "用户登录" 是构造函数参数,ActionName 是命名参数。
通过反射可以检查某个方法是否被特定特性标记,并获取其数据。
static void Main()
{
var method = typeof(Program).GetMethod("Login");
var attribute = method.GetCustomAttribute
if (attribute != null)
{
Console.WriteLine($"动作描述: {attribute.ActionName}");
}
// 执行方法
Login();}
输出结果:
动作描述: Authentication 执行登录操作这种机制常用于日志记录、权限验证、序列化控制、API 文档生成等场景。
基本上就这些。自定义特性不复杂但容易忽略细节,比如作用目标和是否允许多次使用(AllowMultiple),记得用 AttributeUsage 明确约束。
以上就是C#的特性(Attribute)是什么?如何创建和使用自定义特性?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号