在许多情况下,我们需要一种方法,能够从元数据中访问属性,c#提供了对映射的支持以访问元数据。通过初始化memberinfo类型对象,system.reflection名字空间中的这个对象可以用来发现成员的属性,对元数据进行访问。
system.reflection.memberinfoinf=typeof(mymath);
对mymath类型调用typeof操作符,它返回一个由继承memberinfo而生成的type类型的变量。
下一步是对memberinfo对象调用getcustomattributes,并将希望得到的属性的类型作为一个参数传递给getcustomattributes。我们将得到一个对象数组,数组的每个成员的类型都是bugfixattribute。
object[]attributes;
attributes=attribute.getcustomattributes(inf,typeof(bugfixattribute));
我们就可以遍历这个数组了,打印bugfixattribute对象的数组,代码下所示:
属性的打印
publicstaticvoidmain()
{
mymathmm=newmymath();
console.writeline("callingdofunc(7).result:{0}",
mm.dofunc1(7));
//获取成员信息并使用它访问自定义的属性
system.reflection.memberinfoinf=typeof(mymath);
object[]attributes;
attributes=
attribute.getcustomattributes(inf,typeof(bugfixattribute));
//遍历所有的属性
foreach(objectattributeinattributes)
{
bugfixattributebfa=(bugfixattribute)attribute;
console.writeline("\nbugid:{0}",bfa.bugid);
console.writeline("programmer:{0}",bfa.programmer);
console.writeline("date:{0}",bfa.date);
console.writeline("comment:{0}",bfa.comment);
}
}
类型发现
我们可以通过映象的方法来研究一个组合实体的内容,如果要建立需要显示组合体内部信息的工具或动态地调用组合体中的途径,这一方法是非常有用的。
通过映象的方法,我们可以知道一个模块、方法、域、属性的类型,以及该类型的每个方法的信号、该类支持的界面和该类的超级类。我们可以通过如下的形式,用assembly.load静态方法动态地加载一个组合体:
publicstaticassembly.load(assemblyname)
然后,可以将它传递到核心库中。
assemblya=assembly.load("mscorlib.dll");
一旦加载了组合体,我们可以通过调用gettypes返回一个type对象数组。type对象是映射的核心,它表示类、界面、数组、值和枚举等的类型定义。
type[]types=a.gettypes();
组合休会返回一个类型的数组,我们可以使用foreach-loop结构显示该数组,其输出将有好几页文档之多,下面我们从中找一小段:
typeissystem.typecode
typeissystem.security.util.stringexpressionset
typeissystem.text.utf7encoding$encoder
typeissystem.argiterator
typeissystem.runtime.remoting.jitlookuptable
1205typesfound
我们得到了一个内容为核心库中类型的数组,可以将它们都打印出来,该数组将有1205个项。
对一种类型映射我们也可以对组合体中一种类型进行映射。为此,我们可以使用gettype方法从组合体中解析出一个类型: