您将如何发出类型的默认值?

sir*_*lot 5 c# reflection reflection.emit

我想实现一个自动清除所有本地字段的接口,到目前为止我有:

// 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);
Run Code Online (Sandbox Code Playgroud)

如何设置保存字段上的默认值的最后一步?

Pet*_*hie 4

就像是:

clearMethodILGen.Emit(OpCodes.Ldfld, localField);
clearMethodILGen.Emit(OpCodes.Initobj, localField.FieldType);
Run Code Online (Sandbox Code Playgroud)