Attribute 特性

特性可以给附加特性的对象附加元数据,附加一些信息,比如长度不能超过20(MaxLength=20),然后用反射获取数据(获取MaxLength)。

(元数据记录了这个程序集里有多少个namespace、多少个类、类里有什么成员、成员的访问级别是什么……而且,元数据是以文本(也就是Unicode字符)形式存在的,使用.NET的反射(Reflection)技术,很容易就能把它们读取出来。一个程序集(.EXE.DLL)能够使用包含在自己体内的元数据来完整地说明自己,而不必像C/C++那样带着一大捆头文件,这就叫作“自包含性”或“自描述性”。)

自定义特性

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;
        }
    }
}

原理:http://blog.csdn.net/FantasiaX/article/details/1636913

posted @ 2018-03-12 17:52  双子牧场主  阅读(118)  评论(0)    收藏  举报