确保unsigned int/long始终在C#中的已检查上下文中执行 [英] Making sure unsigned int/long always execute in checked context in C#

查看:117
本文介绍了确保unsigned int/long始终在C#中的已检查上下文中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人发现uint和ulong的默认上下文是未选中的,而不是考虑到它们表示永远不会为负的值而选中的,这使我们感到奇怪吗?

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..).

是否存在可以应用于任何类/程序集的现有属性,以便始终在受检查的上下文中执行算术运算?我正在考虑自己写一个(作为使用PostSharp的一个方面),但是如果已经有一个,那就太好了.

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.

非常感谢,

推荐答案

我看不出有符号整数与有符号整数相比有什么不同...为什么从0到uint.MaxValue的下溢比下溢更好从int.MinValueint.MaxValue?

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?

如果您希望通过检查来编译整个程序集,只需在命令行或Visual Studio中使用/checked(或更明确地使用/checked+),在项目属性下找到生成"选项卡,单击高级...",然后选中检查算术上溢/下溢"框.

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.

这篇关于确保unsigned int/long始终在C#中的已检查上下文中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆