Mono.Cecil - 如何获取自定义属性

时间:2009-08-06 06:59:55

标签: c# .net reflection mono mono.cecil

我正在尝试使用Cecil检查与给定方法关联的属性。它似乎找到了它,但我无法使用以下代码得到它的名字:

AssemblyDefinition assembly = AssemblyFactory.GetAssembly(pathBin);
assembly.MainModule.Types[0].Methods[1].CustomAttributes[0].ToString()

我知道这必须是我设置我的函数的属性,因为当我从dll中删除它时,第二行代码将变为null。我想做的是能够获得属性的名称。目前第二行代码只返回一个“Mono.Cecil.CustomAttribute”。我猜应该有一种获取属性名称(类类型)名称的方法,对吗?

谢谢!

2 个答案:

答案 0 :(得分:7)

在编写MoMA时我也遇到了麻烦。以下是它使用的代码:

AssemblyDefinition assembly = AssemblyFactory.GetAssembly(pathBin);
assembly.MainModule.Types[0].Methods[1].CustomAttributes[0].Constructor.DeclaringType.ToString()

答案 1 :(得分:-3)

CustomAttributeSystem.Attribute派生类型的实例,因此ToString()将执行作者决定的任何内容。

如果您想了解属性类型,您应该询问其类型:

typeInfo.GetCustomAttributes(false)[0].GetType().ToString() ;

我没有看到你正在使用的这个属性CustomAttributes,所以我宁愿使用我一直使用的方法MemberInfo.GetCustomAttributes(bool)