HTML5技术

【备战面试之】一、特性是什么东东 - 敷衍不起(3)

字号+ 作者:H5之家 来源:H5之家 2015-12-21 09:39 我要评论( )

static void Main( string [] args){System.Reflection.MemberInfo info = typeof (T2Class);TMessgAttribute[] hobbyAttr = (TMessgAttribute[])Attribute.GetCustomAttributes(info, typeof (TMessgAttribute));

static void Main(string[] args) { System.Reflection.MemberInfo info = typeof(T2Class); TMessgAttribute[] hobbyAttr = (TMessgAttribute[])Attribute.GetCustomAttributes(info, typeof(TMessgAttribute));//修改1.这里需要取特性数据的集合了 Console.WriteLine(, info.Name); for (int i = 0; i < hobbyAttr.Count(); i++)//修改2.这里需要循环打印了 { Console.WriteLine(); Console.WriteLine(, hobbyAttr[i].createName); Console.WriteLine(, hobbyAttr[i].createTime); Console.WriteLine(, hobbyAttr[i].mess); Console.WriteLine(, hobbyAttr[i].modifyTime); } Console.ReadKey();

全部代码:

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 = TMessgAttribute : Attribute//1.定义类TMessg加上后缀TMessgAttribute 2.继承Attribute。 { public TMessgAttribute() { } 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; } } 修改时间 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(, info.Name); for (int i = 0; i < hobbyAttr.Count(); i++)//修改2.这里需要循环打印了 { Console.WriteLine(); Console.WriteLine(, hobbyAttr[i].createName); Console.WriteLine(, hobbyAttr[i].createTime); Console.WriteLine(, hobbyAttr[i].mess); Console.WriteLine(, hobbyAttr[i].modifyTime); } Console.ReadKey(); } } [TMessg(, , , modifyTime = )] [TMessg(, , , modifyTime = )] public class TClass { //................ } public class T2Class : TClass { //........... } }

View Code

自定义特性可以干什么?

上面我们通过反编译,发现自定义特性实际上就是一个对象调用的最前面加了一段实例化的代码。

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • HTML5新特性-多线程(Worker SharedWorker) - 大~熊

    HTML5新特性-多线程(Worker SharedWorker) - 大~熊

    2017-04-18 11:01

  • [干货来袭]C#7.0新特性(VS2017可用) - GuZhenYin

    [干货来袭]C#7.0新特性(VS2017可用) - GuZhenYin

    2017-03-10 14:01

  • EntityFramework Core 1.1有哪些新特性呢?我们需要知道 - JeffckyWang

    EntityFramework Core 1.1有哪些新特性呢?我们需要知道 - JeffckyWa

    2017-01-22 18:01

  • 2017年要学习的三个CSS新特性 - 绿岛之北

    2017年要学习的三个CSS新特性 - 绿岛之北

    2017-01-20 14:01

网友点评
o