Fork me on GitHub

特性(attribute)

 自定义特性

class Program
    {
        static void Main(string[] args)
        {

            Console.ReadLine();
        }
    }
    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
    public class HelpAttribute : Attribute
    {
        protected string description;
        public HelpAttribute(string description_in)
        {
            this.description = description_in;
        }
        public string Description
        {
            get
            {
                return this.description;
            }
        }
        public string name
        { get; set; }
    }
    [Help("this is do Nothing Class", name = "zhangsan")]
    public class AnyClass
    {

    }

 获取特性

HelpAttribute helpAttribute;
            foreach (var attr in typeof(AnyClass).GetCustomAttributes(true))
            {
                helpAttribute = attr as HelpAttribute;
                if (null != helpAttribute)
                {
                    Console.WriteLine("AnyClass Description:{0}", helpAttribute.Description);
                }
            }

 

posted @ 2015-06-05 09:03  乔闻  阅读(145)  评论(0编辑  收藏  举报