C# 如何发出类型的默认值?
我想实现一个自动清除所有本地字段的接口,到目前为止,我有:C# 如何发出类型的默认值?,c#,reflection,reflection.emit,C#,Reflection,Reflection.emit,我想实现一个自动清除所有本地字段的接口,到目前为止,我有: // Implement IClearable dynamicType.AddInterfaceImplementation(typeof(IClearable)); MethodBuilder clearnMethodBuilder = dynamicType.DefineMethod("Clear", MethodAttributes.Public | MethodAttributes.Virtual, CallingConven
// 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);
如何设置最后一步以在字段上保存默认值?类似于:
clearMethodILGen.Emit(OpCodes.Ldfld, localField);
clearMethodILGen.Emit(OpCodes.Initobj, localField.FieldType);
这个有趣吗?是的,这很有帮助。实际上,我发现正确的方法可能是发出Activator.CreateInstance(T)。因为这会自动实例化默认的object.class或struct?如果是后者,您可以执行
this=new StructName()
。第二步中的Ldfld
似乎不合逻辑。是的,刚刚意识到这一点。现在我在清除“Guid”时遇到问题。