特性应用

取得枚举类型的注释

平时开发时,经常会用到枚举类型及其相关判断,而有时我们想显示枚举类型的注释,怎么办?下面用特性来解决这个问题。

namespace AttributeDemo.CustomAttributes
{
public class RemarkAttribute : Attribute
{
private readonly string remark; public RemarkAttribute(string remark)
{
this.remark = remark;
} public string GetRemark()
{
return remark;
}
}
} namespace AttributeDemo.Extensions
{
public enum UserState
{
/// <summary>
/// 正常
/// </summary>
[RemarkAttribute("正常")]
Normal = 0,
/// <summary>
/// 冻结
/// </summary>
[RemarkAttribute("冻结")]
Frozen,
/// <summary>
/// 删除
/// </summary>
[RemarkAttribute("删除")]
Deleted
} public static class RemarkExtension
{
public static string GetRemark(this Enum value)
{
Type type = value.GetType();
FieldInfo field = type.GetField(value.ToString());
if (field.IsDefined(typeof(RemarkAttribute), true))
{
RemarkAttribute attr = field.GetCustomAttribute<RemarkAttribute>();
return attr.GetRemark();
}
return value.ToString();
}
} }

使用

UserState userState = UserState.Normal;
Console.WriteLine(userState.GetRemark());

数据有效性检查

一般对于用户提交的数据,我们都需要进行数据有效性的检查,之后才能提交到数据库。本次我们使用特性,优雅的解决这个问题。

声明检查数据长度的特性(因为想把数据校验作为一个共通处理,因此需要首先声明一个抽象类):

namespace AttributeDemo.CustomAttributes
{ public abstract class CustomValidateAttribute : Attribute
{
public abstract bool Validate(object value);
} public class LengthValidateAttribute : CustomValidateAttribute
{
private readonly int minLen;
private readonly int maxLen; public LengthValidateAttribute(int minLen, int maxLen)
{
this.minLen = minLen;
this.maxLen = maxLen;
} public override bool Validate(object value)
{
if (value != null && !string.IsNullOrEmpty(value.ToString()))
{
int len = value.ToString().Length;
if (len >= minLen && len <= maxLen)
{
return true;
}
}
return false;
}
}
}

把特性附加到类中

namespace AttributeDemo
{
//可以对类整体使用
[CustomAttribute(description:"类特性示例",remark: "类特性")]
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
[LengthValidateAttribute(16, 100)]//追加对邮箱的长度检查
public string EMail { get; set; }
//可以对属性字段使用
[CustomAttribute(description: "属性示例", remark: "属性特性")]
[LengthValidateAttribute(6, 9)]//追加对电话号码的长度检查
public string PhoneNumber { get; set; }
//可以对方法使用
[CustomAttribute(description: "方法示例", remark: "方法特性")]
public void Study()
{
Console.WriteLine($"{Name}正在学习中。。。");
}
//可以对返回值使用
[return: CustomAttribute(description: "返回值示例", remark: "返回值特性")]
public string SayHi([CustomAttribute(description: "参数示例", remark: "参数特性")] string name)//可以对参数列表使用
{
return $"Hello {name}";
}
}
}

再对Student类添加一个扩展方法(如果想对更广泛范围的对象进行数据校验,可以对它们的基类追加扩展方法):

public static class ValidateExtension
{
public static bool Validate(this Student value)
{
int errCount = 0; Type type = value.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.IsDefined(typeof(CustomValidateAttribute), true))
{
IEnumerable<CustomValidateAttribute> attris = property.GetCustomAttributes<CustomValidateAttribute>();
foreach (CustomValidateAttribute attr in attris)
{
if (!attr.Validate(property.GetValue(value)))
{
Console.WriteLine($"数据校验失败:字段[{property.Name}]");
errCount++;
}
}
}
} return errCount == 0 ? true : false;
}
}

调用数据校验:

Student stu = new Student
{
Id = 1,
EMail = "xxxxx@xxxx.com",
Name = "brein",
PhoneNumber = "1234567890"
};
stu.Validate();

输出校验结果:

数据校验失败:字段[PhoneNumber]
数据校验失败:字段[EMail]


以上,是两个平时用的比较多的关于特性的应用场景。在ASP.NET Core中,特性还有更多应用场景,例如:FilterValidateMVC/API相关特性, AOP应用等等。可以说特性无处不在且非常重要。充分掌握特性相关知识,是掌握ASP.NET Core的充分必要条件。

【C#特性】 Attribute 应用的更多相关文章

  1. [C#] 剖析 AssemblyInfo.cs - 了解常用的特性 Attribute

    剖析 AssemblyInfo.cs - 了解常用的特性 Attribute [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5944391.html 序 ...

  2. [C#] C# 知识回顾 - 特性 Attribute

    C# 知识回顾 - 特性 Attribute [博主]反骨仔 [原文地址]http://www.cnblogs.com/liqingwen/p/5911289.html 目录 特性简介 使用特性 特性 ...

  3. C# 知识特性 Attribute

    C#知识--获取特性 Attribute 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集.类型.方法.属性等)相关联.特性与程序实体关联后,可在运行时使用"反射"查询 ...

  4. 区分元素特性attribute和对象属性property

    × 目录 [1]定义 [2]共有 [3]例外[4]特殊[5]自定义[6]混淆[7]总结 前面的话 其实attribute和property两个单词,翻译出来都是属性,但是<javascript高 ...

  5. .Net内置特性Attribute介绍

    特性Attribute概述 特性(Attribute)是一种特殊的类型,可以加载到程序集或者程序集的类型上,这些类型包括模块.类.接口.结构.构造函数.方法.字段等,加载了特性的类型称之为特性的目标. ...

  6. 【点滴积累】通过特性(Attribute)为枚举添加更多的信息

    转:http://www.cnblogs.com/IPrograming/archive/2013/05/26/Enum_DescriptionAttribute.html [点滴积累]通过特性(At ...

  7. 理解特性attribute 和 属性property的区别 及相关DOM操作总结

    查一下英语单词解释,两个都可以表示属性.但attribute倾向于解释为特质,而property倾向于解释私有的.这个property的私有解释可以更方便我们下面的理解. 第一部分:区别点 第一点:  ...

  8. 如何获取类或属性的自定义特性(Attribute)

    如何获取类或属性的自定义特性(Attribute) 问题说明: 在ActiveRecord或者其他的ORM等代码中, 我们经常可以看到自定义特性(Attribute)的存在(如下面的代码所示) [Pr ...

  9. C# 知识特性 Attribute,XMLSerialize,

    C#知识--获取特性 Attribute 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集.类型.方法.属性等)相关联.特性与程序实体关联后,可在运行时使用“反射”查询特性,获取特性集合方 ...

  10. c#特性attribute:

    特性是被编译到metadata中,  是提供给反射用的. 特性attribute:1 什么是attribute,和注释有什么区别 2 声明和使用attribute3 使用attribute完成扩展4 ...

随机推荐

  1. 记一次redis 基于spring实现类对同一个KEY序列化内容不同导致一次事故

    我们的场景是这样的 我们对一个key:比如list.point.card:1 @Resourceprivate RedisTemplate<String, Long> redisTempl ...

  2. golang中的标准库数据格式

    数据格式介绍 是系统中数据交互不可缺少的内容 这里主要介绍JSON.XML.MSGPack JSON json是完全独立于语言的文本格式,是k-v的形式 name:zs 应用场景:前后端交互,系统间数 ...

  3. 磁盘sda,hda,sda1,并行,串行

    1.sd,hd表示硬盘, a表示第一块盘, 1表示硬盘上的第一个分区 2.sd是Serial ATA Disk ,表示硬盘是scsi,SATA串行接口 hd是 hard disk,表示硬盘是IDE(也 ...

  4. Java继承的概念与实现

    // 方法 public class Demo { public static void main(String[] args) { Teacher t = new Teacher(); t.name ...

  5. 数据库查询语句遇到:Unknown column 'XXXX' in 'where clause'解决方法

    数据库查询语句遇到:Unknown colunm 'XXX' in 'where clause'解决方法 根本原因:可能是sql语句所用到的数据类型错误(int与String)弄错- 我的情况: 在网 ...

  6. 搭建BBS博客系统

    目录 一:搭建BBS项目 1.部署数据库 2.启动数据库 3.进入数据库 4.远程连接MySQL数据 5.pycham连接Mysql 二:开始部署BBS 1.上传代码 2.数据库迁移 3.删除文件 4 ...

  7. django之js模板插件artTemplate的使用

    安装: 方式1:artTemplate模板源码下载地址:https://aui.github.io/art-template/zh-cn/index.html 方式2:使用node.js进行安装:np ...

  8. 如何在 VS Code 中为 Java 类生成序列化版本号

    前言 IDEA 提供自动生成序列化版本号的功能,其实 VS Code 也可以,只是默认关闭了这个功能,下面就来看看如何开启这个功能吧. 配置过程 首先需要保证 VS Code 上安装了提供 Java ...

  9. application/x-www-form-urlencoded、application/json、multipart/form-data、text/xml简单总结

    最近在数据传输时,一直不明白这四种的区别,查了很多资料,也还是感到很模糊,因此,简单总结一下,以后再完善 1.在GET方式传输数据中,这四种格式,后台都可以接收数据(原生的request.getPar ...

  10. ARC和MRC兼容和转换

    1.ARC模式下如何兼容非ARC的类 转变为非ARC -fno-objc-arc 转变为ARC的, -f-objc-arc (不常用) 2.如何将MRC转换为ARC