开发者

c# emit check a bool field and break to a label

I want to check a bool field if it is false. But I can not get it to work.

So I want to push a bool field to the stack and call the Brtrue_S, this will turn over control is a value is true or not null. But it fail. This code is working fine if I only push a int, say a 0, to the stack, why not an boolean?

I have try some unbox_any, but my know how on this, is not that good.

FieldBuilder fieldId = proxy.DefineField("Is" + property.Name + "Init", typeof (Boolean),
                                                                 FieldAttributes.Private);


Label ExitIfStatement = getIL.DefineLabel();
//getIL.Emit(OpCodes.Ldc_I4_0); // push 0 to the eval stack, this WORKS FINE!

//getIL.Emit(OpCodes.Ldfld, fieldId); // push 0 to the eval stack // THIS FAILD, WHY ? 

getIL.Emit(OpCodes.Brtrue_S, ExitIfStatement); // if is[propertyName]init == true goto MarkLabel(ExitIfStatement)
getIL.EmitWriteLine("Test if null is true");
getIL.Emit(OpCodes.Nop);

getIL.MarkLabel(ExitIfStatement);
getIL.EmitWriteLine("Test if null: false");                 
getIL.Emit(OpCodes.Nop);

getIL.Emit(OpCodes.Ldar开发者_开发百科g_0); // push the type on stack we need it to call base property
getIL.Emit(OpCodes.Call, propertyInfo.GetGetMethod()); // TEST CODE
getIL.Emit(OpCodes.Ret);


When you access a field you need to reference it correctly by pushing this onto the stack first:

getIL.Emit(OpCodes.Ldarg_0);
getIL.Emit(OpCodes.Ldfld, fieldId);


Because your bool is not initialized?

"NullReferenceException is thrown if the object is null and the field is not static" (see msdn)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜