我想分配一个大型整数数组来测试 LongCount 运算符。当 quote 时使用 LongCount 运算符:
you expect the result to be greater than MaxValue.
所以为了准备我的测试,我想分配一个整数数组,它只比 Int32.MaxValue
大一点:
Int64[] arr = new Int64[Int32.MaxValue + 10UL];
但这会抛出一个OverflowException
。
我想做的是这样的:
Int64[] arr = new Int64[Int32.MaxValue + 10UL];
var res = arr.LongCount();
然后期望 res
为 2147483657
(即 Int32.MaxValue + 10
)。
我该怎么做?
最佳答案
您可以编写自己的列表实现来存储多个数组并将它们链接在一起(或者很可能已经有更好的某个地方......)。将巨大的 ulong
int 映射到两个 Int32
索引以到达那里,在其上实现 IEnumerable
接口(interface),然后进行测试。
ulong listSize = Int32.MaxValue + 10UL;
BigList<bool> myList = new BigList<bool>(listSize);
Debug.Assert(myList.LongCount() == (long)listSize);
Console.ReadKey();
示例实现..
public class BigList<T> : IEnumerable<T>
{
private List<T[]> _storage = new List<T[]>();
private const int _maxStorageArraySize = 1000;
public ulong Capacity { get; private set; }
public BigList(ulong capacity)
{
_storage = new List<T[]>();
Capacity = capacity;
int arraysRequired = (int)Math.Ceiling((double)capacity / (double)_maxStorageArraySize);
int lastArraySize = (int)(capacity % (ulong)_maxStorageArraySize);
for (int i = 0; i < arraysRequired; i++)
_storage.Add(new T[(i + 1) < arraysRequired ? _maxStorageArraySize : lastArraySize]);
}
public T this[ulong idx]
{
get
{
int arrayIdx = (int)(idx / (ulong)_maxStorageArraySize);
int arrayOff = (int)(idx % (ulong)_maxStorageArraySize);
return _storage[arrayIdx][arrayOff];
}
set
{
int arrayIdx = (int)(idx / (ulong)_maxStorageArraySize);
int arrayOff = (int)(idx % (ulong)_maxStorageArraySize);
_storage[arrayIdx][arrayOff] = value;
}
}
public class BigListEnumerator : IEnumerator<T>
{
private BigList<T> _bigList;
private ulong _idx;
public BigListEnumerator(BigList<T> bigList)
{
_bigList = bigList;
}
public T Current
{
get { return _bigList[_idx]; }
}
public void Dispose()
{
_bigList = null;
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
return _idx++ < _bigList.Capacity;
}
public void Reset()
{
_idx = 0;
}
}
public IEnumerator<T> GetEnumerator()
{
return new BigListEnumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new BigListEnumerator(this);
}
}
关于c# - 如何创建大型整数数组来测试 LongCount?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30823370/