使用Cecil调用EqualityComparer.Default

时间:2016-08-22 10:16:36

标签: c# generics mono.cecil

如何使用Mono Cecil生成必要的IL代码来调用System.Collections.Generic.EqualityComparer<T>.get_Default方法?

我尝试了类似的变种,但是从PEVerify无法解析令牌,而Cecil抱怨某些东西来自另一个模块并且需要导入到Cecil本身的ArgumentOutOfRangeException之后,我遇到了各种错误。

泛型类型参数来自我正在处理的属性的PropertyType

PropertyDefinition propertyDef = ...;
var equalityComparer = typeDef.Module.ImportReference(typeof(System.Collections.Generic.EqualityComparer<>));
var equalityComparerInst = equalityComparer.MakeGenericInstanceType(propDef.PropertyType);
var getDefaultMethod = equalityComparerInst.Resolve().Methods.First(m => m.Name == "get_Default");
var getDefaultMethodRef = typeDef.Module.ImportReference(getDefaultMethod, getDefaultMethod);
il.Append(il.Create(OpCodes.Call, getDefaultMethodRef));

我需要哪些代码?

来自其他模块的通用实例总是很棘手。

1 个答案:

答案 0 :(得分:1)

这应该有效

 private static void CallEqualityComparerDefault()
 {
     string assemblyPath = $"{Environment.CurrentDirectory}\\ClassLibrary1.dll";
     var mainModule = AssemblyDefinition.ReadAssembly(assemblyPath).MainModule;

     var methodDef = mainModule.Types.First(
         type => type.Name == "TestClass").Methods.Single(m => m.Name == "TestMethod");

     var eq = mainModule.Import(typeof(EqualityComparer<>));
     var obj = mainModule.Import(typeof(object));
     var genericEq = new GenericInstanceType(eq);
     genericEq.GenericArguments.Add(obj);
     var importedGenericEq = mainModule.Import(genericEq);
     var defaultMethodDef = importedGenericEq.Resolve().Methods.Single(m => m.Name == "get_Default");
     var methodRef =  mainModule.Import(defaultMethodDef);
     methodRef.DeclaringType = importedGenericEq;

     var ilProcessor = methodDef.Body.GetILProcessor();
     ilProcessor.InsertBefore(
         ilProcessor.Body.Instructions.First(), 
         Instruction.Create(OpCodes.Callvirt, methodRef));
     methodDef.Body.OptimizeMacros();

     mainModule.Write(assemblyPath + ".new.dll");
 }

ClassLibrary是一个包含名为TestClass的类型的dll,其中包含方法TestMethod

在我将调用添加到EqualityComparer<>.Default之前,方法正文如下所示:

IL_0000: nop
IL_0001: ret

之后:

IL_0000: callvirt class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<object>::get_Default()
IL_0005: nop
IL_0006: ret