• 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.结果

    欢迎指正:haizi2014@qq.com
  • 相关阅读:
    random模块的随机变换
    re模块与正则表达式进阶
    面向对象整体细化
    __new__内部工作方式
    前端之CSS
    前端之HTML
    数据库
    同步异步阻塞非阻塞
    进程间的通信
    day 36(多进程)
  • 原文地址:https://www.cnblogs.com/hcfan/p/5164135.html
Copyright © 2020-2023  润新知