C#特性

目录

C#特性

1. 概括

C#中的特性是一种用于向代码元素添加元数据的机制。它们允许程序员在代码中添加额外的信息,以影响程序的行为、编译过程或提供其他元数据。特性在编写现代C#代码时变得越来越常见,因为它们提供了一种优雅的方法来实现元数据驱动的开发。

特性分为:框架自带特性(如:RequiredAuthorizeRouteHttpPost等)和自定义特性,都继承System.Attribute

2. 语法

定义特性类

以下是一个简单的特性类定义示例:

csharp 复制代码
using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class MyCustomAttribute : Attribute
{
    public string Description { get; }

    public MyCustomAttribute(string description)
    {
        Description = description;
    }
}

应用特性

将特性应用到代码元素上,可以使用以下语法:

csharp 复制代码
    [MyCustom("类使用自定义特性")]
    public class MyClass
    {
        [MyCustom("方法使用自定义特性")]
        public void MyMethod()
        {
        }
    }

获取特性

要获取 MyCustom 特性,您可以使用反射来检查某个类型或成员上是否应用了该特性,并且访问该特性的属性。下面是如何获取 MyCustom 特性的示例代码:

csharp 复制代码
// 获取 MyClass 类上的 MyCustom 特性
var classAttributes = typeof(MyClass).GetCustomAttributes(typeof(MyCustomAttribute), false);
foreach (MyCustomAttribute attribute in classAttributes)
{
    Console.WriteLine($"MyClass类使用的MyCustom特性: {attribute.Description}");
}

// 获取 MyClass 类中 MyMethod 方法上的 MyCustom 特性
var methodInfo = typeof(MyClass).GetMethod("MyMethod");
var methodAttributes = methodInfo.GetCustomAttributes(typeof(MyCustomAttribute), false);
foreach (MyCustomAttribute attribute in methodAttributes)
{
    Console.WriteLine($"MyMethod方法使用的MyCustom特性: {attribute.Description}");
}

3. 应用场景

数据验证

在模型类上应用特性,以进行数据验证。例如,使用DataAnnotations中的特性来验证模型:

csharp 复制代码
public class User
{
    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    [Range(18, 99)]
    public int Age { get; set; }
}

序列化和反序列化

控制对象的序列化和反序列化过程。例如,使用Json.NET中的特性来指定JSON属性的名称和行为:

csharp 复制代码
public class Product
{
    [JsonProperty("product_name")]
    public string Name { get; set; }

    [JsonIgnore]
    public decimal Price { get; set; }
}

描述性元数据

为枚举值或其他代码元素添加描述信息。例如,使用DescriptionAttribute为枚举值添加描述信息:

csharp 复制代码
public enum Status
{
    [Description("The task is pending")]
    Pending,

    [Description("The task is completed")]
    Completed
}

依赖注入

在依赖注入容器中标记服务以进行注入。例如,在ASP.NET Core中,使用[Inject]特性标记需要注入的服务:

csharp 复制代码
[Inject]
public class MyService
{
    // This property will be injected by the DI container
}

单元测试

在单元测试框架中使用特性标记测试方法。例如,在NUnit中使用[Test]特性标记测试方法:

csharp 复制代码
[Test]
public void TestMethod()
{
    // Test code here
}

权限控制

使用特性进行权限控制。例如,在ASP.NET Core中使用[Authorize]特性标记需要授权的控制器或操作方法:

csharp 复制代码
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    // Only accessible to users in the Admin role
}

AOP(面向切面编程)

通过特性实现AOP,如日志记录、事务管理等。例如,在ASP.NET Core中使用ActionFilterAttribute来实现日志记录:

csharp 复制代码
public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Log action execution start
        base.OnActionExecuting(context);
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        // Log action execution end
        base.OnActionExecuted(context);
    }
}

总结

C#中的特性为程序员提供了一种强大的元数据驱动机制,可以应用于多种场景。通过在代码中定义和使用特性,可以增强代码的可读性、可维护性,并提供灵活的方式来控制程序的行为和属性。

引用

  1. 博文示例代码 https://github.com/chi8708/DotNetNote/blob/master/Note.Basic/11Attribute.cs
相关推荐
魔法阵维护师1 小时前
从零开发游戏需要学习的c#模块,第三十五章(打包发布 —— 让别人玩你的游戏)
学习·游戏·c#
iCxhust1 小时前
C# 程序,实现二进制文件十六进制查看器,支持按行定位
开发语言·单片机·嵌入式硬件·c#·微机原理·8086最小系统·8088单板机
Xin_ye100862 小时前
C# 零基础到精通教程 - WPF 专题二:数据绑定与 MVVM
开发语言·c#·wpf
Xin_ye100862 小时前
C# 零基础到精通教程 - WPF 专题一:WPF 入门与 XAML 基础
c#·wpf
兆。2 小时前
LangChain文档处理集成指南:面向知识管理开发者
开发语言·langchain·c#
_oP_i2 小时前
105、word 出现 {TOCO“1-2“HZ}
开发语言·c#·word
影寂ldy3 小时前
C#构造函数 + 析构函数
开发语言·c#
影寂ldy19 小时前
C# 类和对象
开发语言·c#
z落落21 小时前
C# 构造函数(无参/有参/重载/this)+析构函数(终结器)|GC 垃圾回收
java·开发语言·c#
z落落21 小时前
C# 字段与属性(get/set访问器、三种属性写法、只读属性)+属性拦截例子(get动态计算 + set数据校验)
开发语言·c#