the*_*onk 4 c# biginteger unchecked c#-4.0
只是注意到在使用BigInteger时未经检查的上下文不起作用,例如:
unchecked
{
// no exception, long1 assigned to -1 as expected
var long1 = (long)ulong.Parse(ulong.MaxValue.ToString());
}
unchecked
{
var bigInt = BigInteger.Parse(ulong.MaxValue.ToString());
// throws overflow exception
var long2 = (long)bigInt;
}
Run Code Online (Sandbox Code Playgroud)
知道为什么会这样吗?大整数转换为其他原始整数类型的方式有什么特别之处吗?
谢谢,
Eri*_*ert 18
C#编译器不知道BigInteger在逻辑上是一个"整数类型".它只是看到一个用户定义的类型,用户定义的显式转换为long.从编译器的角度来看,
long long2 = (long)bigInt;
Run Code Online (Sandbox Code Playgroud)
与以下内容完全相同:
long long2 = someObject.SomeMethodWithAFunnyNameThatReturnsALong();
Run Code Online (Sandbox Code Playgroud)
它没有能力进入该方法并告诉它停止抛出异常.
但是当编译器看到时
int x = (int) someLong;
Run Code Online (Sandbox Code Playgroud)
在编译器中生成的代码做转换,所以可以选择,因为它认为合适的方式产生选中或取消选中代码.
请记住,"已检查"和"未选中"在运行时无效; 当控件进入未经检查的上下文时,它不像CLR进入"未选中模式"."checked"和"unchecked"是编译器关于在块内生成什么类型的代码的指令.它们只在编译时有效,并且BigInt转换为long的编译已经发生.它的行为是固定的.
| 归档时间: |
|
| 查看次数: |
434 次 |
| 最近记录: |