Attribute 特性

特性能夠給附加特性的對象附加元數據,附加一些信息,好比長度不能超過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;
        }
    }
}

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

相關文章
相關標籤/搜索