我有一个返回 System.Numerics.BigInteger
的属性。当我将属性转换为 int 时,出现此错误。
无法将类型“System.Numerics.BigInteger”转换为“int”
如何在 C# 中将 int 与 System.Numerics.BigInteger
相互转换?
最佳答案
conversion from BigInteger to 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?)"
这是有效的(尽管如果值太大而不适合 int
变量,它可能会在运行时抛出异常):
BigInteger big = ...
int result = (int)big; // works
请注意,如果 BigInteger
值被装箱在一个 object
中,您不能同时将其拆箱并转换为 int
:
BigInteger original = ...;
object obj = original; // box value
int result = (int)obj; // runtime error
// "Specified cast is not valid."
这个有效:
BigInteger original = ...;
object obj = original; // box value
BigInteger big = (BigInteger)obj; // unbox value
int result = (int)big; // works
关于c# - 在 C# 中将 int 转换为 System.Numerics.BigInteger/从 System.Numerics.BigInteger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7127565/