I'm trying to make a setter in IL emit, but this setter must only accept objects which are not null, if not, it must throw an exception. This is my class Notnull which recieves a il Generator and a FieldBuilder in which the setter (if not null) must store its value.
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);
}
}
Class utils which I call in the IL and throws my exception.
class Utils
{
public void checkIfNull(object obj)
{
if (obj == null) throw new MyException();
}
}
When I try to create my new type (which has this IL) it presents a Disconnected context error.
Aucun commentaire:
Enregistrer un commentaire