(uint) index >= (uint)_size 比 index >= _size 好吗?

问题描述 投票:0回答:2

我查看了

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
有评论说明否则。

问题: 除溢出外,将整数转换为无符号整数的概念是什么,在什么特定情况下对开发人员有用?

c# .net vector data-structures dynamic-arrays
2个回答
1
投票

重点是一步处理负数和正数。

如果将负数赋给

uint
,结果保证大于
int.MaxValue
。因此,任何负索引都将无法通过
(uint) index >= (uint)_size
检查。如果您移除石膏,则需要进行两项检查:
index < 0 || index >= _size
。由于演员表是“免费的”,这最终会稍微提高性能。


0
投票

视情况而定。假设索引总是正数,从 0 到 400000000。在这种情况下,最好使用 uint!:

int(32 位)的限制是:

 int: –2147483648 to 2147483647 
 uint: 0 to 4294967295 
© www.soinside.com 2019 - 2024. All rights reserved.