【转】一、特性是什么东东
2018-01-11 11:03
267 查看
前言
我们初学C#的时候看到类上面一对中括号里面有个高亮了的关键字,不知道那是什么有什么用。想问人又不知道它叫什么。纠结的要命。其实,它就是特性。如:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace net { [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]//3.设置可用于哪些对象 public class TMessgAttribute : Attribute//1.定义类TMessg加上后缀TMessgAttribute 2.继承Attribute。 { public TMessgAttribute() { } /// <param name="createTime">创建时间</param> /// <param name="createName">创建人</param> public TMessgAttribute(string createTime, string createName, string mess) { this._createName = createName; this._createTime = createTime; this._mess = mess; } private string _createTime; public string createTime { get { return _createTime; }//4.只能有get方法 } private string _createName; public string createName { get { return _createName; } } private string _mess; public string mess { get { return _mess; } } /// <summary> /// 修改时间 /// </summary> public string modifyTime { get; set; } } class Program { static void Main(string[] args) { System.Reflection.MemberInfo info = typeof(T2Class); TMessgAttribute[] hobbyAttr = (TMessgAttribute[])Attribute.GetCustomAttributes(info, typeof(TMessgAttribute));//修改1.这里需要取特性数据的集合了 Console.WriteLine("类名:{0}", info.Name); for (int i = 0; i < hobbyAttr.Count(); i++)//修改2.这里需要循环打印了 { Console.WriteLine("================================================"); Console.WriteLine("创建人:{0}", hobbyAttr[i].createName); Console.WriteLine("创建时间:{0}", hobbyAttr[i].createTime); Console.WriteLine("备注消息:{0}", hobbyAttr[i].mess); Console.WriteLine("修改时间:{0}", hobbyAttr[i].modifyTime); } Console.ReadKey(); } } [TMessg("2015-12-20", "zhaopei", "我只是测试自定义特性,不要报错哦,求求你了。", modifyTime = "2015-12-21")] [TMessg("2015-12-21", "zhaopei", "我再次测试,还能给我面子显示出来吗?", modifyTime = "2015-12-22")] public class TClass { //................ } public class T2Class : TClass { //........... } }View Code
自定义特性可以干什么?
上面我们通过反编译,发现自定义特性实际上就是一个对象调用的最前面加了一段实例化的代码。
那么我们可以做的事可多了,除了像上面一样为对象设置“注释”,我们还可以自定义个特性,给某些方法或是某些类做“操作日志记录”,或者给需要在执行某些方法的时候需要权限,我们可以做个权限认证的特性等等。
这里就需要大家自己去扩展了。
本文已同步至《C#基础知识巩固系列》
相关文章推荐
- 【备战面试之】一、特性是什么东东
- [巩固C#] 一、特性是什么东东
- 特性是什么东东?
- (转)事务是什么,以及事务四个特性
- <![CDATA[ ]]> 是什么东东
- 什么是事务?事务的特性有哪些?
- 从前台体验角度聊聊搜索是个什么东东
- 6 BasicView到底是什么东东
- 开源、自由软件和GNU是什么东东?
- AWE GAE MEGOO 和 提高性能的INTEL的C++重新编译 BigTable是什么东东
- 什么是windows PE 告诉你Windows PE是什么东东?详细介绍一下winpe精简系统
- CDN是什么东东
- struts2中ActionContext是什么东东???
- 对于新手而言,PHP开发选择什么开发工具,及PhpStorm的特性和Git集成要点
- UTF-8 是什么东东?
- WEB2.0是什么东东?[转]
- PHP继承体系当中的多态——什么情况下会表现出多态特性?
- 【软工视频】--软工是什么东东?
- “=>”是什么东东?
- 事务是什么?事务的四大特性? jdbc如何做事务处理?