VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 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


复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
CSHARP
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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
CSHARP
//1.声明 public class TableNameAttribute:Attribute { private string _name = null; //初始化构造函数 public TableNameAttribute(string tablename) { this._name = tablename; } public string GetTableName() { return this._name; } }

在这里插入图片描述 然后再student前面加上自定义特性 在这里插入图片描述 实现特性的扩展方法


复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
CSHARP
//通过反射获取表名 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项目,不容错过的还有书籍,手写笔记,壁纸分享 等。

本文作者:迷恋自留地

本文链接:https://www.cnblogs.com/netcore5/p/14590778.html



相关教程