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

时间:2013-03-29 15:42:36

标签: 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);

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

1 个答案:

答案 0 :(得分:4)

类似的东西:

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