zoukankan      html  css  js  c++  java
  • 自定义Attribute类

        在我们的项目中有时经常会标识一些类的特性,在下面我们将简短的方式来介绍如何构建自定义的Attribute类。    

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DLPVideoApp.DLPCtrl
    {
        // 摘要:
        //     定义宿主程序的识别码。
        [ComVisible(true)]
        [AttributeUsage(AttributeTargets.Class, Inherited = true)]
        public sealed class MyClassAttribute : Attribute
        {
            private string _identify = "";
            // 摘要:
            //     初始化 System.Reflection.AssemblyTitleAttribute 类的新实例。
            //
            // 参数:
            //   identifyNumber:
            //     识别码。
            public MyClassAttribute(string identifyType)
            {
                _identify = identifyType;
            }
    
            public string IdentifyType
            {
                get
                {
                    return _identify;
                }
            }
        }
    }
    

     在定义完一个继承自Attribute的基类之后,接下来就是如何去应用我们自定义的MyClassAttribute类了,其实也非常简单,我们只需要在要标明类属性的上面添加下面的内容即可:[MyClassAttribute("DLPVideoApp.DLPCtrl.DLPWin")](这里仅仅是举出一个案例)

      接下来就是如何去应用该Attribute了,下面通过反射的方式来获取程序集中所有的类相关信息,然后再来匹配名称为[MyClassAttribute("DLPVideoApp.DLPCtrl.DLPWin")]的类。

    Assembly exeAssembly = Assembly.GetExecutingAssembly();
                Type[] types = exeAssembly.GetExportedTypes();
                Type winType = null;
                for (int i = 0; i <= types.Length - 1; i++)
                {
                    Type t = types[i];
                    if (!(t.IsPublic && t.IsClass == true && t.IsAbstract == false)) continue;
    
    
                    object[] clsAttrs = t.GetCustomAttributes(typeof(MyClassAttribute), false);
                    if (clsAttrs == null || clsAttrs.Length == 0) continue;
    
                    MyClassAttribute myClassAtribute = clsAttrs[0] as MyClassAttribute;
                    if (myClassAtribute.IdentifyType == "DLPVideoApp.DLPCtrl.DLPWin")
                    {
                        winType = t;
                        break;
                    }
                }
    

      Assembly exeAssembly = Assembly.GetExecutingAssembly(); Type[] types = exeAssembly.GetExportedTypes();通过这种方式能够获取一个程序集中所有的类以及事件,通过遍历Type数组来寻找自定义的Attribute类,这种方式有时还是非常有效的。另外还要记得去反思怎样正确使用类的属性。

  • 相关阅读:
    存储:块存储/文件存储/对象存储
    系统调用system call以及strace/dtruss
    JBoss EAP应用服务器部署方法和JBoss 开发JMS消息服务小例子
    在IE中,JS方法名和input的name重名时,调用该方法无效
    html 使表格随着内容自动适应宽度
    Jboss 安全和优化
    java网页数据抓取实例
    Eclipse+Weblogic 12开发简单的Enterprise Application
    eclipse中整合ejb和web工程
    破解 jar 包之直接修改 .class 文件方式
  • 原文地址:https://www.cnblogs.com/seekdream/p/5121787.html
Copyright © 2011-2022 走看看