在工做或者学习中,不免或多或少的接触到特性这个东西,可能你不太清楚什么是特性,那么我给你们举两个例子 [Obsolete],[HttpGet],[HttpPost],[Serizlized],[AuthorizeFilter] (总有你见过的一个吧) 。有没有以为好熟悉,下面跟着小赵一探究竟。git
特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其余信息。github
特性(Attribute)的名称和值是在方括号内规定的,放置在它所应用的元素以前。positional_parameters 规定必需的信息,name_parameter 规定可选的信息。数据库
特性的定义:直接或者间接的继承 Attribute 类缓存
定义完就直接能够在方法前面用 [CustomAttribute] 能够省略 Attribute 写成[Custom]mvc
在特性类上面的特性
/// AttributeTargets.All --能够修饰的应用属性
/// AllowMultiple = true ---是否能够进行屡次修饰
[AttributeUsage(AttributeTargets.All,AllowMultiple = true)]
ide
特性自己是没有啥用,可是能够经过反射来使用,增长功能,不会破坏原有的封装
经过反射,发现特性 --实例化特性--使用特性
经过特性获取表名(orm)就是一个很好的案例函数
首先定义个类,伪装和数据库中的表结构同样,但代表是t_student
能够经过两个方法来获取表名(方法1加字段,或者扩展方法tostring,但都破坏了之前的封装,不提倡这样作),而后就用到今天学习的特性attribute
了学习
public class Student { //public static string tablename = "t_student"; //public string tostring() //{ // return "t_student"; //} public int id { get; set; } public string Name { get; set; } public int Sex { get; set; } }
在定义特性类TableNameAttribute
this
//1.声明 public class TableNameAttribute:Attribute { private string _name = null; //初始化构造函数 public TableNameAttribute(string tablename) { this._name = tablename; } public string GetTableName() { return this._name; } }
而后再student前面加上自定义特性
实现特性的扩展方法编码
//经过反射获取表名 public static string GetName(Type type) { if (type.IsDefined(typeof(TableNameAttribute),true)) { TableNameAttribute attribute =(TableNameAttribute)type.GetCustomAttribute(typeof(TableNameAttribute), true); return attribute.GetTableName(); } else { return type.Name; } }
F5执行,查看运行结果
特性自己是没有啥用,可是能够经过反射来使用,增长功能,不会破坏原有的封装
项目我放再个人github
https://github.com/PrideJoy/NetTemple/tree/master/特性
分享最新的Net和Core相关技术以及实战技巧,更重要的是分享Net项目,不容错过的还有书籍,手写笔记,壁纸分享 等。