c# - C# 中值类型 BigInteger 的限制是什么?

标签 c# .net numerical value-type

如 MSDN 中所述 BigInteger是:

An immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.

据我所知,BigInteger 是一个 ValueType,据我所知,ValueType 的最大大小必须为 16 字节

MSDN 进一步说:

an OutOfMemoryException can be thrown for any operation that causes a BigInteger value to grow too large.

还有更多:

Although this process is transparent to the caller, it does incur a performance penalty. In some cases, especially when repeated operations are performed in a loop on very large BigInteger values

它如何存储这么大的值,如 double.MaxValue + double.MaxValue 一样大? 有人告诉我它里面有 ReferenceType 对象,但我在 VisualStudio 的定义中只能找到 ValueTypes。

它的真正极限是什么?即使没有,它如何“作为一种值类型”设法存储所有那么多的数据?

最佳答案

As I can see BigInteger is a ValueType, as much as I know, a ValueType must have a maximum size of 16 bytes.

不,那不是真的。这是一个约定俗成的限制,但对于值类型来说,接受更多的限制是完全可行的。例如:

public struct Foo {
    private readonly int a, b, c, d, e; // Look ma, 20 bytes!
}

但是,我强烈怀疑 BigInteger 实际上包含对字节数组的引用:

public struct BigInteger {
    private readonly byte[] data;
    // Some other fields...
}

( Moslem Ben Dhaou's answer 显示了一个使用 intuint[] 的当前实现,当然,细节是有意隐藏的。 )

所以 BigIntegervalue 仍然可以很小,但它可以引用一大块内存 - 如果没有足够的内存来分配什么当你执行某些操作时需要,你会得到一个异常。

How could it store such big values, as big as double.MaxValue + double.MaxValue ?

BigInteger 用于整数,所以我不会特别想将它用于与double 相关的任何事情......但是从根本上说,限制将取决于您拥有多少内存以及 CLR 可以处理的数组大小。实际上,在实际达到任何特定数字的限制之前,您可能会谈论巨大数字 - 但如果您有数以亿计的较小数字,那显然也需要很大的内存。

关于c# - C# 中值类型 BigInteger 的限制是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21856753/

相关文章:

c# - 如何在 .NET 中以 SOLID 方式实现库级跟踪和诊断?

c# - WebSocket 关闭数据包

c# - 在 LINQ 之外使用匿名类型是一件好事吗?

c# - 带有只读 getter 的属性有什么好处?

math - 相机远离环面时射线与环面方程相交的数值错误

C# - 如何从路径中提取文件名和扩展名?

c# - 将 C# 字符串作为参数发送到非托管 C++ DLL 函数

algorithm - 我正在尝试使用 maple 编写梯形规则程序

c# - Resharper 正确吗?

牛顿与二分法的javascript实现