Mono.Cecil - How to get custom attributes

蹲街弑〆低调 提交于 2019-12-23 12:42:14

问题


I am trying to use Cecil to inspect the attributes associated with a given method. It seems to find it, but I cannot get its name using the following code:

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

I know this must be the attribute I've set my function to, because when I remove it from the dll, the second line of code will turn out to null. What I'd like to do is be able to get the attribute's name. Currently the second line of code will return just a "Mono.Cecil.CustomAttribute". I'd guess there should be a way of getting an attribute's name(class type) name, right?

Thanks!


回答1:


I had trouble with this when writing MoMA as well. Here is the code it uses:

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



回答2:


A CustomAttribute is an instance of a System.Attribute derived Type, so ToString() will do whatever the author decided.

If you want to know about attribute types you should ask for their type:

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

I haven't seen this property CustomAttributes you are using, so I rather used the method MemberInfo.GetCustomAttributes(bool) which I always use.



来源:https://stackoverflow.com/questions/1237345/mono-cecil-how-to-get-custom-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!