简体   繁体   English

用Mono.Cecil注入GeneratedCodeAttribute

[英]Injecting GeneratedCodeAttribute with Mono.Cecil

I'm manupulating my .net 2.0 assemblies with Mono.Cecil. 我正在用Mono.Cecil处理.net 2.0程序集。 After manipulation I want to mark assembly as processed by injecting a module attribute 操作后,我想通过注入模块属性将程序集标记为已处理

var stringType = _module.Import(typeof(string));
var baseCtor = _module.Import(typeof(GeneratedCodeAttribute).GetConstructor(new[] { typeof(string), typeof(string) }));
var result = new CustomAttribute(baseCtor);
result.ConstructorArguments.Add(new CustomAttributeArgument(stringType, "ProcessedBySomething"));
result.ConstructorArguments.Add(new CustomAttributeArgument(stringType, "1.0"));

After saving the assembly it become dependent on .net 4.0, since manipulating app is written in .net 4.0. 保存程序集后,由于操纵应用程序是用.net 4.0编写的,因此它依赖于.net 4.0。 GeneratedCodeAttribute exists in .net 2.0, so what am I doing wrong? .net 2.0中存在GeneratedCodeAttribute,所以我做错了什么?

You're guessing right. 你猜对了。 Since the manipulating application is running on .net 4.0, typeof being a runtime feature, it will return a type for the current runtime version. 由于操纵的应用程序在.net 4.0上运行,因此typeof是运行时功能,它将返回当前运行时版本的类型。

To fix it, the simple thing to do is to create references for the mscorlib version referenced by the module you're modifying, using Cecil to open the assembly. 要解决此问题,最简单的方法是使用Cecil打开程序集,为要修改的模块所引用的mscorlib版本创建引用。 Your code would become: 您的代码将变为:

var stringType = _module.TypeSystem.String;
var corlib = (AssemblyNameReference) _module.TypeSystem.Corlib;
var system = _module.AssemblyResolver.Resolve (new AssemblyNameReference ("System", corlib.Version) {
    PublicKeyToken = corlib.PublicKeyToken,
});
var generatedCodeAttribute = system.MainModule.GetType ("System.CodeDom.Compiler.GeneratedCodeAttribute");
var generatedCodeCtor = generatedCodeAttribute.Methods.First (m => m.IsConstructor && m.Parameters.Count == 2);

var result = new CustomAttribute (_module.Import (generatedCodeCtor));
result.ConstructorArguments.Add(new CustomAttributeArgument(stringType, "ProcessedBySomething"));
result.ConstructorArguments.Add(new CustomAttributeArgument(stringType, "1.0"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM