自定义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类,这种方式有时还是非常有效的。另外还要记得去反思怎样正确使用类的属性。

原文地址:https://www.cnblogs.com/seekdream/p/5121787.html