1

我想使用 Mono.Cecil 为方法添加自定义属性。自定义属性的构造函数有一个System.Type. 我试图弄清楚如何使用 Mono.Cecil 创建这样的自定义属性以及 System.Type 参数的参数是什么。

我的属性定义如下:

public class SampleAttribute : Attribute {
    public SampleAttribute (Type type) {}
}

到目前为止,我已经尝试过:

var module = ...;
var method = ...;
var sampleAttributeCtor = ...;

var attribute = new CustomAttribute (sampleAttributeCtor);

attribute.ConstructorArguments.Add (
    new ConstructorArgument (module.TypeSystem.String, module.GetType ("TestType").FullName));

但这似乎不起作用。任何想法?

我已将代码更新如下

var module=targetExe.MainModule;
            var anothermodule=sampleDll.MainModule;
            var custatt = new CustomAttribute(ctorReference);


            var corlib =module .AssemblyResolver.Resolve((AssemblyNameReference)module.TypeSystem.Corlib);
            var systemTypeRef = module.Import(corlib.MainModule .GetType("System.Type"));
            custatt.ConstructorArguments.Add(new CustomAttributeArgument(systemTypeRef, module.Import(anothermodule.GetType("SampleDll.Annotation"))));
            methodDef.CustomAttributes.Add(custatt);

有什么建议么?

4

1 回答 1

2

即使自定义属性中的类型使用它们的全名作为字符串进行编码,Cecil 也会为您抽象出来。

Mono.Cecil 中类型的表示是 a TypeReference(或者TypeDefinition如果类型来自同一模块,则为 a)。

您只需将其作为参数传递。首先,您需要获取对System.Type用作自定义属性参数类型的类型的引用。

var corlib = module.AssemblyResolver.Resolve ((AssemblyNameReference) module.TypeSystem.Corlib);
var systemTypeRef = module.Import (corlib.GetType ("System.Type"));

然后根据您想要用作参数的类型,您可以编写:

attribute.ConstructorArguments.Add (
    new ConstructorArgument (
        systemTypeRef,
        module.GetType ("TestType")));

或者如果您感兴趣的类型在另一个模块中,则需要导入引用:

attribute.ConstructorArguments.Add (
    new ConstructorArgument (
        systemTypeRef,
        module.Import (anotherModule.GetType ("TestType"))));
于 2012-10-17T10:29:05.800 回答