c# - 使用 Mono.Cecil 注入(inject) generatedCodeAttribute

标签 c# mono mono.cecil

我正在使用 Mono.Cecil 操作我的 .net 2.0 程序集。 操作后,我想通过注入(inject)模块属性将程序集标记为已处理

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"));

保存程序集后,它会依赖于.net 4.0,因为操作应用程序是用.net 4.0编写的。 GenerationCodeAttribute 存在于 .net 2.0 中,那么我做错了什么?

最佳答案

你猜对了。由于操作应用程序在 .net 4.0 上运行,typeof 是一个运行时功能,因此它将返回当前运行时版本的类型。

要解决此问题,最简单的方法是为您正在修改的模块引用的 mscorlib 版本创建引用,并使用 Cecil 打开程序集。您的代码将变为:

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"));

关于c# - 使用 Mono.Cecil 注入(inject) generatedCodeAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4712265/

相关文章:

c# - 寻找一个简单的.net 动画库

c# - Action 和 ActionLink 不适用于 ASP.NET Mono Razor View

c# - 按契约(Contract)进行静态检查设计

.net - Mono 上的 MEF 无法正常工作?

c# - 确定 Mono.Cecil.MethodDefinition 是否引用与给定 EnvDTE.CodeFunction 相同的函数

c# - 通过代码零或一关系映射

C# 到 VB.Net : Why does this fail to compile when converted to VB?

c# - AppContextSwitchOverrides 不起作用,在授权上下文中发现 3 个 DNS 声明

c# - 成员在另一个模块中声明,需要导入

.net - Mono.Cecil 如何定义输出参数