How did you choose the default value for the type?

I want to implement an interface that automatically clears all local fields, as long as I have:

// Implement IClearable
dynamicType.AddInterfaceImplementation(typeof(IClearable));

MethodBuilder clearnMethodBuilder = dynamicType.DefineMethod("Clear", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard);
ILGenerator clearMethodILGen = clearnMethodBuilder.GetILGenerator();

foreach (FieldBuilder localField in fields)
{
    clearMethodILGen.Emit(OpCodes.Ldarg_0);
    clearMethodILGen.Emit(OpCodes.Ldfld, localField);
    clearMethodILGen.Emit(OpCodes.??, Profit??);
}

clearMethodILGen.Emit(OpCodes.Ret);

How to set the last step to save the default value in a field?

+5
source share
1 answer

sort of:

clearMethodILGen.Emit(OpCodes.Ldfld, localField);
clearMethodILGen.Emit(OpCodes.Initobj, localField.FieldType);
+4
source

All Articles