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 自定义特性可以干什么?上面我们通过反编译,发现自定义特性实际上就是一个对象调用的最前面加了一段实例化的代码。