勾选和未勾选有什么区别?

发布于 2024-09-24 12:02:23 字数 118 浏览 0 评论 0原文

有什么区别

checked(a + b)

和 和

unchecked(a + b)

What is the difference between

checked(a + b)

and

unchecked(a + b)

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

潇烟暮雨 2024-10-01 12:02:23

这些运算符检查(或不检查)结果数值运算中是否存在溢出。在 checked 情况下,如果操作结果超出数据类型允许的最小值或最大值,则会引发 OverflowException 异常。

更多信息可从 MSDN 获取。

Those are operators that check (or do not check) for overflow in the resulting numerical operation. In the checked case, an OverflowException exception is raised if the result of the operation exceeds the minimum or maximum value allowed for the datatype.

More information is available from MSDN.

向日葵 2024-10-01 12:02:23

它控制整数运算的溢出检查

It controls overflow checking for integer operations.

潜移默化 2024-10-01 12:02:23

如果 a + b 大于数据类型的最大值,checked 将抛出异常。未选中将滚动该值的溢出并将其添加到零。

if a + b is larger than the maximum value of the datatype, checked will throw an exception. Unchecked will roll the overflow of the value and add it to zero.

与往事干杯 2024-10-01 12:02:23

语言规范有一篇关于差异的好文章。

检查和非检查运算符用于控制整数类型算术运算和转换的溢出检查上下文。

class Test
{
   static readonly int x = 1000000;
   static readonly int y = 1000000;
   static int F() {
      return checked(x * y);      // Throws OverflowException
   }
   static int G() {
      return unchecked(x * y);   // Returns -727379968
   }
   static int H() {
      return x * y;               // Depends on default
   }
}

The Language Specification has a good article on the differences.

The checked and unchecked operators are used to control the overflow checking context for integral-type arithmetic operations and conversions.

class Test
{
   static readonly int x = 1000000;
   static readonly int y = 1000000;
   static int F() {
      return checked(x * y);      // Throws OverflowException
   }
   static int G() {
      return unchecked(x * y);   // Returns -727379968
   }
   static int H() {
      return x * y;               // Depends on default
   }
}
莫言歌 2024-10-01 12:02:23

其他答案涵盖了两者之间的区别。值得注意的一件事是,如果 a 和 b 是浮点数,则没有区别。它仅适用于整数运算。

您还可以设置一个构建选项,以便检查所有内容。这意味着您的应用程序运行速度会稍微慢一些,但您不需要对算术运算进行检查。

这是一篇很好的文章,描述了一些陷阱: http://www.codeproject.com/ KB/cs/overflow_checking.aspx

The other answers cover the difference between the two. One thing worth noting is that if a and b are floats there will be no difference. It only works for integer operations.

There is also a build option you can set so everything is checked. This will mean your app runs slightly slower but you won't need to put checked around your arithmetic operations.

Here is a nice writeup that describes some pitfalls: http://www.codeproject.com/KB/cs/overflow_checking.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文