zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    11 数据的增删改
    10 外键的变种 三种关系
    09 完整性约束
    03 body标签中的相关标签
    02 body标签中的相关标签
    01 HTML介绍和head标签
    08 数据类型(2)
    07 数据类型
    06 表的操作
    偶遇RecyclerView内部Bug
  • 原文地址:https://www.cnblogs.com/hcfan/p/5164135.html
Copyright © 2011-2022 走看看