【问题标题】:Mono.Cecil - How to get custom attributesMono.Cecil - 如何获取自定义属性
【发布时间】:2015-08-18 17:15:38
【问题描述】:

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

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

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

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 有趣。这也是我现在使用的。
    • 我是从 Cecil 的作者那里得到的,所以我认为这是唯一的方法。
    • 我无法在任何地方找到“AssemblyFactory”类。我找到了所有其他课程,但没有找到这个。似乎这个类不存在于 mono.cecil dll 中。它是否存在于其他命名空间中?谁能帮帮我。
    • 新版 Cecil (0.9.4) 有不同的 API。加载程序集的等价物是 AssemblyDefinition.ReadAssembly()。
    【解决方案2】:

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

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

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

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

    【讨论】:

    • 是的,但我没有使用反射,我使用的是 cecil。这看起来像反射,对吧?
    猜你喜欢
    • 2012-01-13
    • 2010-10-29
    • 2013-04-16
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多