c# - 在 C# 中将 int 转换为 System.Numerics.BigInteger/从 System.Numerics.BigInteger

标签 c# casting biginteger

我有一个返回 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/

相关文章:

c# - 通过 .NET Azure SDK 扩展云服务实例计数?

c# - 在没有 XNA 的 Windows Phone 中点击并拖动手势

oop - 自动将对象扩展到某个继承类

java - 为什么我的字节数组显示的长度错误?

java - 任意精度的精确含义是什么?

c# - 如何实现网页的实时数据

c# - 将泛型类型参数显式转换为任何接口(interface)

java - 在java中将字符数组转换为对象数组?是否可以?

rust - 如何将 char 转换为整数并在 Rust 中匹配武器?

Java BigInteger 源代码性能基准测试