2009-08-06 145 views
4

我正在尝试使用Cecil来检查与给定方法关联的属性。这似乎找到它,但使用下面的代码我无法得到它的名字:Mono.Cecil - 如何获得自定义属性

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

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

谢谢!

回答

7

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

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

有趣。那也是我现在使用的。 – 2009-08-06 16:03:42

+3

我是从Cecil的作者那里得到的,所以我认为这是唯一的方法。 – jpobst 2009-08-06 16:24:03

+0

+1:很好,谢谢 – 2009-11-09 12:58:41

-3

一个CustomAttributeSystem.Attribute派生类型的实例,因此ToString()将尽一切笔者决定。

如果你想了解的属性类型,你应该问他们类型:

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

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

+0

是的,但我没有使用反射,我正在使用塞西尔。这看起来像反思,对吧? – 2009-08-06 16:07:12

+3

-1:问题是关于Mono.Cecil,而不是System.Reflection。 – ShdNx 2011-03-20 15:05:12