Ved*_*ant 2 .net c# vector dynamic-arrays data-structures
我深入研究List<T>并发现了以下代码:
public T this[int index] {
get {
// Following trick can reduce the range check by one
if ((uint) index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
Contract.EndContractBlock();
return _items[index];
}
set {
if ((uint) index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
Contract.EndContractBlock();
_items[index] = value;
_version++;
}
}
Run Code Online (Sandbox Code Playgroud)
在这两个if语句中,indexand _size(类型为Int32) 都被转换为UInt32,我知道这不是因为溢出,因为首先。if有一个注释指出 other
问题: 除了溢出之外,将整数转换为无符号整数的概念是什么?在什么特定情况下它对开发人员有用?
重点是一步处理负数和正数。
如果将负数转换为uint,则结果保证大于int.MaxValue。因此任何负索引都会导致(uint) index >= (uint)_size检查失败。如果移除石膏,则需要进行两项检查index < 0 || index >= _size:由于演员阵容是“自由”的,这最终会稍微提高性能。
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |