如何发出类型的默认值?

5

我希望实现一个接口,自动清除所有本地字段,目前我已经有了以下代码:

// 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
这个对你有兴趣吗?https://dev59.com/RGkv5IYBdhLWcg3wtTG7 - Matthew Watson
是的,这很有帮助。实际上,我发现正确的方法可能是发出 Activator.CreateInstance(T)。因为它会自动实例化默认对象。 - sircodesalot
类还是结构体?如果是后者,你可以使用 this = new StructName() - leppie
1
第二步中的 Ldfld 似乎不合逻辑。 - leppie
是的,刚刚意识到了。现在我只是遇到了清除“Guid”的问题。 - sircodesalot
你如何定义某种类型的默认值?似乎你不是指 default(T),但在这种情况下,你需要明确说明你的意思。 - svick
1个回答

4

something like:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接