Making sure unsigned int/long always execute in checked context in C#

有些话、适合烂在心里 提交于 2020-01-24 08:49:10

问题


Has anyone found it strange that the default context for uint and ulong is unchecked rather than checked considering that they are meant to represent values that can never be negative?

So if some code is trying to violate that constraint it seems to me the natural and preferred behaviour would be to throw an exception rather than returning the max value instead (which can easily leave important pieces of data in an invalid state and impossible to revert..).

Is there an existing attribute which can be applied to either class/assembly so that it always performs arithmetic operations in a checked context? I was thinking of writing one myself (as an aspect using PostSharp) but would be great if there's one already.

Many thanks,


回答1:


I don't see what's different about unsigned integers here compared with signed ones... why is underflowing from 0 to uint.MaxValue likely to be better than underflowing from int.MinValue to int.MaxValue?

If you want a whole assembly to be compiled with checking, just use /checked (or /checked+ to be more explicit) on the command line or in Visual Studio, under the project properties find the Build tab, click "Advanced..." and tick the "Check for arithmetic overflow/underflow" box.

I don't believe there's any way to do this just for a particular class.



来源:https://stackoverflow.com/questions/2772379/making-sure-unsigned-int-long-always-execute-in-checked-context-in-c-sharp

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