Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Reflection;
- using Mono.Cecil;
- namespace CecilTest
- {
- public interface MyInterface<T>
- {
- T InterfaceMethod();
- }
- public class MyClass : MyInterface<string>
- {
- public string InterfaceMethod()
- {
- return "MyClass.InterfaceMethod()";
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine(new MyClass().InterfaceMethod());
- var inputAssemblyPath = Assembly.GetEntryAssembly().Location;
- var entryAssembly = AssemblyFactory.GetAssembly(inputAssemblyPath);
- var mainModule = entryAssembly.Modules.Cast<ModuleDefinition>().First();
- var types = mainModule.Types;
- var MyInterfaceT = types[1];
- var MyInterfaceTMethod = MyInterfaceT.Methods[0];
- var MyInterfaceString = types[2].Interfaces[0];
- // According to you:
- var MyInterfaceStringMethod = MakeGeneric(MyInterfaceTMethod, MyInterfaceString);
- Console.WriteLine(MyInterfaceStringMethod.MetadataToken); // this outputs Module [0x0000], which looks wrong
- // Try to set the method override to MyInterfaceStringMethod
- types[2].Methods[0].Overrides.Add(MyInterfaceStringMethod);
- AssemblyFactory.SaveAssembly(entryAssembly, @"C:\temp\output.exe"); // change the path as needed
- // Now open output.exe in ildasm and look at MyClass.InterfaceMethod(). It'll say:
- //
- // .override 'INVALID TOKEN: 0x06000000'
- //
- // Observe that it's now Method [0x0000]...
- // The correct token would have been MemberRef [0x0001], although I don't know why
- }
- static MethodReference MakeGeneric(MethodReference method, TypeReference declaringType)
- {
- var reference = new MethodReference(method.Name, declaringType, method.ReturnType.ReturnType, method.HasThis, method.ExplicitThis, MethodCallingConvention.Generic);
- foreach (ParameterDefinition parameter in method.Parameters)
- reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));
- return reference;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment