mercredi 15 novembre 2023

ILGenerator: How to get the value of the current object (owner) to call the ToString method

I have only recently started studying ILGenerator, so I will be glad of any explanations on this topic. Below is the code where there is a line to add the value of the current object (owner) to the stack:

MethodInfo debugLog = typeof(Console).GetMethod(nameof(Console.WriteLine),
   BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(object) }, null);

MethodInfo toString = GetType().GetMethod(nameof(ToString),
   BindingFlags.Public | BindingFlags.Instance);            

DynamicMethod setterMethod = new DynamicMethod("MyMethod", 
   MethodAttributes.Public, 
   CallingConventions.Standard, 
   null, 
   null, 
   typeof(TestClass), 
   true);

ILGenerator gen = setterMethod.GetILGenerator();

/*What code should I use?*/
/*gen.Emit(OpCodes.???);*/

gen.Emit(OpCodes.Call, toString);
gen.Emit(OpCodes.Call, debugLog);

gen.Emit(OpCodes.Ret);

setterMethod.Invoke(this, null);




Aucun commentaire:

Enregistrer un commentaire