简体   繁体   English

为什么c#List实现在“保证容量”方法中指定此确切值?

[英]why does c# List implementation specify this exact value in the ensure capacity method?

using ILspy the code is : 使用ILspy的代码是:

private void EnsureCapacity(int min)
{
if (this._items.Length < min)
{
    int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
    if (num > 2146435071)
    {
        num = 2146435071;
    }
    if (num < min)
    {
        num = min;
    }
    this.Capacity = num;
}
}

why is it checking if the num is greater than 2146435071 specifically shouldn't it just check for underflow & set num=Int.Max or anyother value greater than min? 为什么要检查num是否大于2146435071,特别是不应该仅检查下溢并设置num = Int.Max或任何其他大于min的值?

This is connected to a fact, that List<T> uses array as internal storage, and maximum array size is set to 2146435071 . 这与事实有关, List<T>使用数组作为内部存储,并且最大数组大小设置为2146435071

Read What is the maximum length of an array in .NET on 64-bit Windows about array max size. 阅读有关数组最大大小的64位Windows上.NET中数组的最大长度是多少

You can easily create your own IList<T> implementation which will not use array as internal storage, and will allow more than 2146435071 elements. 您可以轻松创建自己的IList<T>实现,该实现将不使用数组作为内部存储,并且将允许2146435071元素。 Of course, you're still limited by int.MaxValue as max number of elements, because IList<T>.Count returns int . 当然,您仍然受到int.MaxValue作为最大元素数的限制,因为IList<T>.Count返回int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM