pro*_*eek 5 c# casting biginteger
我有一个返回的属性System.Numerics.BigInteger.当我将属性转换为int时,我收到此错误.
Cannot convert type 'System.Numerics.BigInteger' to 'int'
如何System.Numerics.BigInteger在C#中将int转换为/从?
从BigInteger到Int32的转换是显式的,因此仅将BigInteger变量/属性赋值给变量int不起作用:
BigInteger big = ...
int result = big; // compiler error:
// "Cannot implicitly convert type
// 'System.Numerics.BigInteger' to 'int'.
// An explicit conversion exists (are you
// missing a cast?)"
Run Code Online (Sandbox Code Playgroud)
这有效(尽管如果值太大而无法容纳int变量,它可能会在运行时抛出异常):
BigInteger big = ...
int result = (int)big; // works
Run Code Online (Sandbox Code Playgroud)
请注意,如果该BigInteger值在object框中输入,则无法将其取消装箱并同时将其转换为int:
BigInteger original = ...;
object obj = original; // box value
int result = (int)obj; // runtime error
// "Specified cast is not valid."
Run Code Online (Sandbox Code Playgroud)
这有效:
BigInteger original = ...;
object obj = original; // box value
BigInteger big = (BigInteger)obj; // unbox value
int result = (int)big; // works
Run Code Online (Sandbox Code Playgroud)