C#特性有哪些
更新:HHH   时间:2023-1-7


本篇内容介绍了“C#特性有哪些”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

前言

在工作或者学习中,难免或多或少的接触到特性这个东西,可能你不太清楚什么是特性,那么我给大家举两个例子  [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执行,查看运行结果

“C#特性有哪些”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注天达云网站,小编将为大家输出更多高质量的实用文章!

返回编程语言教程...