【C#特性】 Attribute 应用
特性应用
取得枚举类型的注释
平时开发时,经常会用到枚举类型及其相关判断,而有时我们想显示枚举类型的注释,怎么办?下面用特性来解决这个问题。
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
中,特性还有更多应用场景,例如:Filter
,Validate
,MVC
/API
相关特性,AOP
应用等等。可以说特性无处不在且非常重要。充分掌握特性相关知识,是掌握ASP.NET Core
的充分必要条件。
【C#特性】 Attribute 应用的更多相关文章
- [C#] 剖析 AssemblyInfo.cs - 了解常用的特性 Attribute
剖析 AssemblyInfo.cs - 了解常用的特性 Attribute [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5944391.html 序 ...
- [C#] C# 知识回顾 - 特性 Attribute
C# 知识回顾 - 特性 Attribute [博主]反骨仔 [原文地址]http://www.cnblogs.com/liqingwen/p/5911289.html 目录 特性简介 使用特性 特性 ...
- C# 知识特性 Attribute
C#知识--获取特性 Attribute 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集.类型.方法.属性等)相关联.特性与程序实体关联后,可在运行时使用"反射"查询 ...
- 区分元素特性attribute和对象属性property
× 目录 [1]定义 [2]共有 [3]例外[4]特殊[5]自定义[6]混淆[7]总结 前面的话 其实attribute和property两个单词,翻译出来都是属性,但是<javascript高 ...
- .Net内置特性Attribute介绍
特性Attribute概述 特性(Attribute)是一种特殊的类型,可以加载到程序集或者程序集的类型上,这些类型包括模块.类.接口.结构.构造函数.方法.字段等,加载了特性的类型称之为特性的目标. ...
- 【点滴积累】通过特性(Attribute)为枚举添加更多的信息
转:http://www.cnblogs.com/IPrograming/archive/2013/05/26/Enum_DescriptionAttribute.html [点滴积累]通过特性(At ...
- 理解特性attribute 和 属性property的区别 及相关DOM操作总结
查一下英语单词解释,两个都可以表示属性.但attribute倾向于解释为特质,而property倾向于解释私有的.这个property的私有解释可以更方便我们下面的理解. 第一部分:区别点 第一点: ...
- 如何获取类或属性的自定义特性(Attribute)
如何获取类或属性的自定义特性(Attribute) 问题说明: 在ActiveRecord或者其他的ORM等代码中, 我们经常可以看到自定义特性(Attribute)的存在(如下面的代码所示) [Pr ...
- C# 知识特性 Attribute,XMLSerialize,
C#知识--获取特性 Attribute 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集.类型.方法.属性等)相关联.特性与程序实体关联后,可在运行时使用“反射”查询特性,获取特性集合方 ...
- c#特性attribute:
特性是被编译到metadata中, 是提供给反射用的. 特性attribute:1 什么是attribute,和注释有什么区别 2 声明和使用attribute3 使用attribute完成扩展4 ...
随机推荐
- SQL查询字段,起别名,列参与数学运算
13.简单查询 13.1.查询一个字段? select 字段名 from 表名: 其中要注意: select和from都是关键字 字段名和表名都是标识符. 强调: 对于SQL语句说,是通用的 所有的S ...
- javaObject类-equals方法及覆盖
1 package face_object; 2 /* 3 * Object:所有类的根类. 4 * Object是不断抽取而来的,具备所有对象都具备的共性内容. 5 * 常用的共性功能: 6 * 7 ...
- Chrome DevTools 面板全攻略
李华西,微医云服务团队前端开发工程师,喜欢瞎折腾,典型猫奴 Console 面板 此章节请打开 devtools/console/console.html 一起食用 一方面用来记录页面在执行过程中的信 ...
- Protobuf 动态加载 .pb 文件并操作 Message
之前写了<Protobuf 动态加载 .proto 文件并操作 Message>.除了直接读取 .proto 文件之外,还有一种类似的方法.先把 .proto 文件编译成 .pb 文件,再 ...
- ExecutorService线程池简单使用
简介 ExecutorService是Java中对线程池定义的一个接口,它位于java.util.concurrent包中,在这个接口中定义了和后台任务执行相关的方法. 常用方法 public < ...
- 详解git fetch与git pull的区别(实操)
感谢原文作者:R-H-R 原文链接:https://blog.csdn.net/riddle1981/article/details/74938111 git fetch和git pull都可以将远端 ...
- java的本地文件操作
一.文件的创建.删除和重命名 File file = new File("/bin/hello.txt");//文件无法被创建,系统找不到指定的路径file.createNewFi ...
- Keepalived配置与使用(1)
介绍 Keepalived是一个基于VRRP协议来实现的WEB服务高可用方案,可以利用其来避免单点故障.一个WEB服务至少会有2台服务器运行Keepalived,一台为主服务器(MASTER),一台为 ...
- Python—字符串常用函数
Python-字符串常用字符串 字符串是一种表示文本的数据类型,使用单引号和双引号及三引号表示 访问字符串中的值字符串的每个字符都对应一个下标,下标编号是从0开始 转义字符字符串的格式化输出切片常用函 ...
- 如何在 pyqt 中实现全局事件总线
前言 在 Qt 中可以使用信号和槽机制很方便地实现部件之间的通信,考虑下面这样的场景: 我想要点击任意一个专辑卡并通知主界面跳转到专辑界面,那么一种实现方式如上图所示:点击任意一个蓝色方框所示的专辑卡 ...