我查看了
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++;
}
}
在两个
if
语句中,index
和_size
(Int32
类型)被强制转换为UInt32
,我知道这不是因为溢出,因为第一个if
有评论说明否则。
问题: 除溢出外,将整数转换为无符号整数的概念是什么,在什么特定情况下对开发人员有用?
重点是一步处理负数和正数。
如果将负数赋给
uint
,结果保证大于int.MaxValue
。因此,任何负索引都将无法通过 (uint) index >= (uint)_size
检查。如果您移除石膏,则需要进行两项检查:index < 0 || index >= _size
。由于演员表是“免费的”,这最终会稍微提高性能。
视情况而定。假设索引总是正数,从 0 到 400000000。在这种情况下,最好使用 uint!:
int(32 位)的限制是:
int: –2147483648 to 2147483647
uint: 0 to 4294967295