C# 特性

1.特性类

 public class FanAttribute : Attribute
    {
        public FanAttribute(string des)
        {
            this._des = des;
        }
        private string _des;

        public string Des
        {
            get { return _des; }
        }
    }//end
 public class haiz : Attribute
    {
        string name;
        public double version;

        public haiz(string name)
        {
            this.name = name;

            // Default value.
            version = 1.0;
        }

        public string GetName()
        {
            return name;
        }
    }//end

2.类中声明特性

 [Fan("ceshi____")]
    [haiz("hc", version = 2.0)]
    public class anyclass
    {
    }//end

3.获取特性方法

public static T getAttr<T>(Type type) where T : class
        {
            T t = default(T);
            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(type); 
            foreach (System.Attribute attr in attrs)
            {
                if (attr is T)
                {
                    t = attr as T;
                    break;
                }
            }
            return t;
        }

4.运行

anyclass a = new anyclass();
            System.Console.WriteLine("{0}", getAttr<haiz>(a.GetType()).GetName());

5.结果

posted @ 2016-01-27 17:50  点点_滴滴  阅读(141)  评论(0编辑  收藏  举报