这是在 Mono.Cecil 中执行的工作代码
之前的C#代码:
public class AnEntityVirtual
{
public virtual string MyData { get; set; }
public virtual bool IsModified { get; set; }
}
set_MyData之前的IL代码:
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld string ClassLibrary1.AnEntityVirtual::'<MyData>k__BackingField'
IL_0007: ret
重写:
// Read the module and get the relevant type
var assemblyPath = $"{Environment.CurrentDirectory}\\ClassLibrary1.dll";
var module = ModuleDefinition.ReadModule(assemblyPath);
var type = module.Types.Single(t => t.Name == "AnEntityVirtual");
// Get the method to rewrite
var myDataProperty = type.Properties.Single(prop => prop.Name == "MyData");
var isModifiedSetMethod = type.Properties.Single(prop => prop.Name == "IsModified").SetMethod;
var setMethodBody = myDataProperty.SetMethod.Body;
// Initilize before rewriting (clear pre instructions, create locals and init them)
setMethodBody.Instructions.Clear();
var localDef = new VariableDefinition(module.TypeSystem.Boolean);
setMethodBody.Variables.Add(localDef);
setMethodBody.InitLocals = true;
// Get fields\methos to use in the new method body
var propBackingField = type.Fields.Single(field => field.Name == $"<{myDataProperty.Name}>k__BackingField");
var equalMethod =
myDataProperty.PropertyType.Resolve().Methods.FirstOrDefault(method => method.Name == "Equals") ??
module.ImportReference(typeof(object)).Resolve().Methods.Single(method => method.Name == "Equales");
var equalMethodReference = module.ImportReference(equalMethod);
// Start the rewriting
var ilProcessor = setMethodBody.GetILProcessor();
// First emit a Ret instruction. This is beacause we want a label to jump if the values are equals
ilProcessor.Emit(OpCodes.Ret);
var ret = setMethodBody.Instructions.First();
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Ldarg_0)); // load 'this'
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Ldfld, propBackingField)); // load backing field
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Ldarg_1)); // load 'value'
ilProcessor.InsertBefore(ret, ilProcessor.Create(equalMethod.IsStatic ? OpCodes.Call : OpCodes.Callvirt, equalMethodReference)); // call equals
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Stloc_0)); // store result
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Ldloc_0)); // load result
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Brtrue_S, ret)); // check result and jump to Ret if are equals
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Ldarg_0)); // load 'this'
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Ldc_I4_1)); // load 1 ('true')
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Call, isModifiedSetMethod)); // set IsModified to 'true'
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Ldarg_0)); // load this
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Ldarg_1)); // load 'value'
ilProcessor.InsertBefore(ret, ilProcessor.Create(OpCodes.Stfld, propBackingField)); // store 'value' in backing field
// here you can call to Notify or whatever you want
module.Write(assemblyPath.Replace(".dll", "_new") + ".dll"); // save the new assembly
之后的C#代码:
public virtual string MyData
{
[CompilerGenerated]
get
{
return this.<MyData>k__BackingField;
}
[CompilerGenerated]
set
{
if (!this.<MyData>k__BackingField.Equals(value))
{
this.IsModified = true;
this.<MyData>k__BackingField = value;
}
}
}
之后的IL代码:
IL_0000: ldarg.0
IL_0001: ldfld string ClassLibrary1.AnEntityVirtual::'<MyData>k__BackingField'
IL_0006: ldarg.1
IL_0007: callvirt instance bool [mscorlib]System.String::Equals(object)
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: brtrue.s IL_001e
IL_0010: ldarg.0
IL_0011: ldc.i4.1
IL_0012: call instance void ClassLibrary1.AnEntityVirtual::set_IsModified(bool)
IL_0017: ldarg.0
IL_0018: ldarg.1
IL_0019: stfld string ClassLibrary1.AnEntityVirtual::'<MyData>k__BackingField'
IL_001e: ret
正如我所写,这是一个如何在 Cecil 中执行此操作的示例。
在您的真实代码中,您可以以此为基础,但需要进行一些更改。
例如,您可以为您的属性创建私有字段,而不使用编译器生成的支持字段。
您可以调用 OptimizeMacros。
此外,如果您确切知道需要重写哪个属性,则可以调用其他相等方法,例如如果是string,可以调用字符串类型的静态方法op_Equality或op?_Inequality这是==和string的!=