我想在IL发出一个setter,但是这个setter只能接受非空的对象,如果不是,它必须抛出一个异常。 这是我的Notnull类,它接收il生成器和FieldBuilder,其中setter(如果不为null)必须存储其值。IL发射断开连接的上下文错误
public class NonNull
{
public void CreateIL(ILGenerator il, FieldBuilder field)
{
il.Emit(OpCodes.Ldarg_0); // Push "this" on the stack
il.Emit(OpCodes.Newobj, typeof(Utils).GetConstructor(new Type[] { }));
il.Emit(OpCodes.Stloc_1);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stloc_2);
il.Emit(OpCodes.Ldloc_2);
il.Emit(OpCodes.Ldloc_1); // Push "value" on the stack
il.Emit(OpCodes.Callvirt,typeof(Utils).GetMethod("checkIfNull"));
il.Emit(OpCodes.Pop);
il.Emit(OpCodes.Ldloc_2);
il.Emit(OpCodes.Stfld, field); // Set the field "_Name" to "value"
il.Emit(OpCodes.Ret);
}
}
我在IL中调用的类utils并抛出我的异常。
class Utils
{
public void checkIfNull(object obj)
{
if (obj == null) throw new MyException();
}
}
当我尝试创建我的新类型(具有此IL)时,它会显示Disconnected上下文错误。
你能发布完整的错误?并假设它是一个例外,包括它的堆栈跟踪? – svick