Operators

2019-02-12  本文已影响0人  津涵

The checked and unchecked Operators 检查/不检查

(1)
Main.cs
byte b = byte.MaxValue; //255
checked
{
b++;
}
Console.WriteLine(b);
运行结果(错误提示):System.OverflowException: Arithmetic operation resulted in an overflow.

(2)You can change this also directly in the csproj project file.可在配置文件中配置
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
</PropertyGroup>

(3)溢出时若不检查,会丢失值
byte b = 255;
unchecked
{
b++;
}
Console.WriteLine(b);
结果:0
注:1)In this case, no exception is raised, but you lose data because the byte type cannot hold a value of 256, the overflowing bits are discarded, and your b variable holds a value of zero (0). ~丢失值
2)Note that unchecked is the default behavior. ~默认是unchecked
3)The only time you are likely to need to explicitly use the unchecked keyword is when you need a few unchecked lines of code inside a larger block that you have explicitly marked as checked. ~unchecked使用场景

(4)By default, overflow and underflow are not checked because enforcing checks has a performance impact. When you use checked as the default setting with your project, the result of every arithmetic operation needs to be verified whether the value is out of bounds. Arithmetic operations are also done with for loops using i++. For not having this performance impact, it’s better to keep the default setting (Check for Arithmetic Overflow/Underflow) unchecked and use the checked operator where needed.
检查会影响性能,可设置默认不检查,在需要检查的部分,显示写明checked

(5)强制类型转换时可进行是否越界的检查
coding:
long val = 3000000000;
int i = checked((int)val);

上一篇下一篇

猜你喜欢

热点阅读