How to use multiple uncheckeds in c#

蓝咒 提交于 2019-12-11 04:16:03

问题


Is there a way to use unchecked for a whole program or a whole block ?

I'm translating something from java that has the type long and lots of comparisons with constants that are unsigned long... Some places there a some switch's with 20~30 cases... Do I have to uncheck every case individualy or is there a faster/easier way to do it?

case 101: 
   return jjMoveStringLiteralDfa5_0(active0, 0x8002010000000000L, active1, 0x1L);

I have to change to:

   return jjMoveStringLiteralDfa5_0(active0, unchecked((long)0x8002010000000000L), active1, 0x1L);

but there are many cases... and it is in a parser generator with lots of IF's, so It would be better to have something to suppress those checks in the whole file instead of searching every possible place that would generate those unsigned long constants...

There is a way to set that on Visual Studio options but since I'm generating a parser I wanted to know if I could make that parser automaticaly not check for overflows/underflows, is that possible?


回答1:


If you want to use hexadecimal literals to express negative integers via the two's complement convention, you simply have to provide both a cast and an explicit use of the unchecked keyword. Example:

sbyte b = unchecked((sbyte)0xAB);
short s = unchecked((short)0xABCD);
int i = unchecked((int)0xABCDABCD);
long l = unchecked((long)0xABCDABCDABCDABCD);

It is not enough that the default context (as defined by C# compiler switch and/or csproj file) is the "unchecked" context.

If you can use the unsigned types (for example uint), you won't have this problem. But the unsigned types are typically not used by the BCL, and are not considered "CLS compliant".


Just make it entirely clear, with positive literals you need neither cast nor unchecked keyword:

sbyte b = 0x2E;
short s = 0x2E3F;
int i = 0x2E3F2E3F;
long l = 0x2E3F2E3F2E3F2E3F;

For constant expressions implicit conversions exist to make this easy, see Implicit constant expression conversions.



来源:https://stackoverflow.com/questions/24252881/how-to-use-multiple-uncheckeds-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!