2012-10-17 61 views
1

我想使用Mono.Cecil将自定义属性添加到方法。自定义属性的构造函数有一个System.Type。我想弄清楚如何用Mono.Cecil创建这样的自定义属性,以及System.Type参数的参数是什么。如何添加将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); 

任何建议,我已经更新的代码?

+0

我不介意回答Mono.Cecil的问题,但你应该让他们更容易阅读和帮助你。提供的代码是混乱的,没有变色,并且可以简化为只有几行,我想你是怎么想的。我要编辑这个问题给你一个例子。 –

回答

2

尽管自定义属性中的类型使用全名作为字符串进行编码,但Cecil会为您抽象。

Mono.Cecil中Type的表示形式为TypeReference(如果类型来自同一个模块,则表示TypeDefinition)。

您只需将其作为参数传递即可。首先,您需要获得对类型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")))); 
+0

嗨,我试过你的解决方案,并得到错误“操作无效,由于对象的当前状态。” –

+0

var custatt = new CustomAttribute(ctorReference); var corlib = inputmodule.AssemblyResolver.Resolve(inputmodule.TypeSystem.Corlib.Name); var systemTypeRef = inputmodule.Import(corlib.GetType()); custatt.ConstructorArguments.Add(new CustomAttributeArgument(systemTypeRef,inputmodule.Import(anothermodule .GetType(“SampleDll.Annotation”)))); methodDef.CustomAttributes.Add(custatt); –

+0

@MuruganAlagesan不,你没有。初始化systemTypeRef的值不是我写的。 –

相关问题