特性能够给附加特性的对象附加元数据,附加一些信息,好比长度不能超过20(MaxLength=20),而后用反射获取数据(获取MaxLength)。spa
(元数据记录了这个程序集里有多少个namespace、多少个类、类里有什么成员、成员的访问级别是什么……并且,元数据是以文本(也就是Unicode字符)形式存在的,使用.NET的反射(Reflection)技术,很容易就能把它们读取出来。一个程序集(.EXE或.DLL)可以使用包含在本身体内的元数据来完整地说明本身,而没必要像C/C++那样带着一大捆头文件,这就叫做“自包含性”或“自描述性”。).net
自定义特性code
namespace AttributeTest { class Program { static void Main(string[] args) { foreach(var pi in typeof(SysInfo).GetProperties()) { CustomAttribute att = Attribute.GetCustomAttribute(pi, typeof(CustomAttribute)) as CustomAttribute; if (att != null) { Console.WriteLine(att.Description); Console.WriteLine(att.Name); } } Console.ReadKey(); } } [AttributeUsage(AttributeTargets.All,AllowMultiple =true)] public class CustomAttribute:Attribute { public string Name { get; set; } public string Description { get; set; } public CustomAttribute(string name) { Name = name; } } public class SysInfo { [Custom("呵呵",Description ="女神之蔑视")] public string Id { get;set; } } }