-
I am trying to rename a field in a generic class. Given this test class: internal class GenericClass<T>
{
private readonly T _value;
public GenericClass(T value)
{
_value = value;
}
} I can locate and rename the var genericType = mod.Types[2];
var genericField = genericType.Fields[0];
genericField.Name = "_valueRenamed"; And I can locate a var genericTypeCtorIl = genericType.Methods[0].Body.Instructions;
var genericFieldRef = genericTypeCtorIl[6].Operand as MemberRef; With this a runtime exception occurs within the constructor because I've noticed that:
I've also tried Edit - complete test code: using System.Reflection;
using dnlib.DotNet;
namespace GenericTest
{
internal class Program
{
static void Main(string[] args)
{
/* Rename GenericTest-renamed.exe back to GenericTest.exe
Construct classes; the modified module will fail here */
new GenericClass<string>(string.Empty);
new NonGenericClass(string.Empty);
/* Load current assembly */
var path = Assembly.GetExecutingAssembly().Location;
var opts = new ModuleCreationOptions(CLRRuntimeReaderKind.CLR);
var modCtx = ModuleDef.CreateModuleContext();
var mod = ModuleDefMD.Load(path, opts);
mod.Context = modCtx;
/* Locate and rename field in GenericClass */
var genericType = mod.Types[2];
var genericField = genericType.Fields[0];
genericField.Name = "_valueRenamed";
var genericTypeCtorIl = genericType.Methods[0].Body.Instructions;
var genericFieldRef = genericTypeCtorIl[6].Operand as MemberRef;
//genericFieldRef.Name = "_valueRenamed"; // Will crash if without
/* Locate and rename field in NonGenericClass */
var nonGenericType = mod.Types[3];
var nonGenericField = nonGenericType.Fields[0];
nonGenericField.Name = "_valueRenamed";
//var nonGenericTypeCtorIl = nonGenericType.Methods[0].Body.Instructions;
//var nonGenericFieldDef = nonGenericTypeCtorIl[6].Operand as FieldDef; // Not needed
mod.Write("GenericTest-renamed.exe");
}
}
internal class GenericClass<T>
{
private readonly T _value;
public GenericClass(T value)
{
_value = value;
}
}
internal class NonGenericClass
{
private readonly object _value;
public NonGenericClass(object value)
{
_value = value;
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You could use |
Beta Was this translation helpful? Give feedback.
You could use
MemberFinder
to find all member refs and defs and then use a dictionary to look up a FieldDef from a MemberRef. See SigComparer, FieldEqualityComparer etc.