首页 > 编程语言 >C#特性

C#特性

时间:2024-05-19 13:30:29浏览次数:14  
标签:MyCustom C# 特性 class 序列化 public

目录

C#特性

1. 概括

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

特性分为:框架自带特性(如:[Required]、[Authorize]、[Route]、[HttpPost]等)和自定义特性,都继承System.Attribute

2. 语法

定义特性类

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

using System;

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

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

应用特性

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

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

获取特性

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


// 获取 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中的特性来验证模型:

public class User
{
    [Required]
    [StringLength(50)]
    public string Name { get; set; }

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

序列化和反序列化

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

public class Product
{
    [JsonProperty("product_name")]
    public string Name { get; set; }

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

描述性元数据

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

public enum Status
{
    [Description("The task is pending")]
    Pending,

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

依赖注入

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

[Inject]
public class MyService
{
    // This property will be injected by the DI container
}

单元测试

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

[Test]
public void TestMethod()
{
    // Test code here
}

权限控制

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

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

AOP(面向切面编程)

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

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

标签:MyCustom,C#,特性,class,序列化,public
From: https://www.cnblogs.com/chi8708/p/18200266

相关文章

  • scss :export 中导出的变量为空
    1.assets/styles/variables.scss$base-menu-color:#bfcbd9;:export{menuColor:$base-menu-color}2.index.vue<template><div:style="{backgroundColor:variables.menuColor}"></div></template><script>im......
  • CSS的Flexbox布局示例详解
    CSSFlexibleBoxModule(简称Flexbox)是一种现代化的布局模式,用于创建响应式的一维布局(无论是水平还是垂直)。它提供了对项目的对齐、方向、排序、尺寸调整等方面的强大控制。下面是对Flexbox布局的一些关键概念和示例代码:一、关键概念FlexContainer(弹性容器):需要添加display:f......
  • 百度 Apollo 自定义安装第三方库(以 libtorch 为例)_apollo 使用自定义库
    CSDN搬家失败,手动导出markdown后再导入博客园百度Apollo是一个非常优秀的自动驾驶框架,但我们平时在开发中也会遇到各种原repo没有处理的问题。笔者近期想用pytorch的C++前端推理模型,但是遇到了libtorch版本与pytorch版本不匹配的问题,因此想自己安装一个新版本的li......
  • 百度 Apollo 使用 bazel 编译 C++ Boost 依赖出现 undefined reference to `boost::pyth
    CSDN搬家失败,手动导出markdown后再导入博客园因为一些原因,楼主想在Apollo自动驾驶框架里使用Boost.python工具来用C++调用Python,从网上找了个例子想编译下试试。C++代码如下(boost.python/EmbeddingPython-PythonWiki):#include<boost/python.hpp>usingnamesp......
  • x64 环境下_findnext() 函数报错——0xC0000005: 写入位置 0xFFFFFFFFDF47C5A0 时发生
    CSDN搬家失败,手动导出markdown后再导入博客园最近在搞单目相机位姿估计,相机标定参考了【OpenCV3学习笔记】相机标定函数calibrateCamera()使用详解(附相机标定程序和数据)提供的代码。/*@paramFile_Directory为文件夹目录@paramFileType为需要查找的文件类型@param......
  • pytorch 踩坑,TypeError: expected seqence object with len>_0 or a single integer_typ
    CSDN搬家失败,手动导出markdown后再导入博客园在看Faster-R-CNN复现代码(https://blog.csdn.net/weixin_44791964/article/details/105739918)的时候,发现推理阶段报错,Dataparallel无法gather参考https://discuss.pytorch.org/t/nn-dataparallel-typeerror-expected-sequence......
  • pytorch 转 tensorRT 踩的几个小坑_tensorrt engine set up failed
    CSDN搬家失败,手动导出markdown后再导入博客园1、版本不匹配[E][TRT]Layer:Where_51'soutputcannotbeusedasshapetensor.[E][TRT]Networkvalidationfailed.[E]Enginecreationfailed.[E]Enginesetupfailed.这实际是由于pytorch与TensorRT版本不匹......
  • scipy_optimize_curve_fit 拟合多维曲面问题_scipy leastsq 拟合曲面
    CSDN搬家失败,手动导出markdown后再导入博客园在做模板匹配算法过程中,想要通过拟合高斯曲面的方式实现亚像素精度。初始代码如下#创建一个函数模型用来生成数据deffunc1(x,a,b,c,d):r=a*np.exp(-((x[0]-b)**2+(x[1]-d)**2)/(2*c**2))......
  • Visual Studio 2015 编写 CUDA 关键字高亮并自动补全_cuda vs 波浪线
    CSDN搬家失败,手动导出markdown后再导入博客园第一步,是在vs2015里面设置vc++文件支持.cu;cuh;文件。方法:工具->选项->文本编辑器->文件扩展名。得到如图所示的界面:注意,在右侧可以添加vc++类型的文件扩展名,这是我的设置效果,操作就不用细说了。![[output/attachme......
  • opencv imshow 函数显示 float64 格式错误_cv2_imshow float
    CSDN搬家失败,手动导出markdown后再导入博客园在模拟高斯光斑的过程中,手动生成了下图所示的图像,使用cv2.imwrite()函数保存正常。![[output/attachments/fa4dbbeff2a5a1f2f99acd241f220fc7_MD5.png]]然而在使用cv2.imshow()函数显示时却出现错误![[output/attachments/e80ba8......