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

原文:http://www.cnblogs.com/seekdream/p/5121787.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值