IT科技类资讯

五分钟完全弄懂C#特性

时间:2010-12-5 17:23:32  作者:人工智能   来源:应用开发  查看:  评论:0
内容摘要:前言在工作或者学习中,难免或多或少的接触到特性这个东西,可能你不太清楚什么是特性,那么我给大家举两个例子 [Obsolete],[HttpGet],[HttpPost],[Serizlized],[A

前言

在工作或者学习中,分钟难免或多或少的完全接触到特性这个东西,可能你不太清楚什么是弄懂特性,那么我给大家举两个例子 [Obsolete],分钟[HttpGet],[HttpPost],[Serizlized],[AuthorizeFilter] (总有你见过的完全一个吧) 。有没有觉得好熟悉,弄懂下面跟着小赵一探究竟。分钟

特性(Attribute)用于添加元数据,完全如编译器指令和注释、弄懂描述、分钟方法、完全类等其他信息。弄懂

特性(Attribute)的分钟名称和值是在方括号内规定的,放置在它所应用的完全元素之前。高防服务器positional_parameters 规定必需的弄懂信息,name_parameter 规定可选的信息。

特性的定义

特性的定义:直接或者间接的继承 Attribute 类

定义完就直接可以在方法前面用 [CustomAttribute] 可以省略 Attribute 写成[Custom]

在特性类上面的特性 /// AttributeTargets.All --可以修饰的应用属性 /// AllowMultiple = true ---是否可以进行多次修饰 [AttributeUsage(AttributeTargets.All,AllowMultiple = true)]图片

特性的使用

特性本身是没有啥用,但是可以通过反射来使用,增加功能,不会破坏原有的封装 通过反射,发现特性 --实例化特性--使用特性 通过特性获取表名(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

//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[1]https://github.com/PrideJoy/NetTemple/tree/master/%E7%89%B9%E6%80%A7

网站模板
copyright © 2025 powered by 益强资讯全景  滇ICP备2023006006号-31sitemap