为什么 Array.Length 是 int,而不是 uint
为什么 Array.Length 是 int,而不是 uint。 这让我很困扰(只是有点),因为长度值永远不可能是负数。
这也迫使我在我自己的类上使用 int 作为长度属性,因为当你 指定一个 int 值,这需要显式转换...
所以最终的问题是:无符号 int (uint
) 有什么用处? 甚至微软似乎也不使用它们。
Why is Array.Length
an int, and not a uint
. This bothers me (just a bit) because a length value can never be negative.
This also forced me to use an int for a length-property on my own class, because when you
specify an int-value, this needs to be cast explicitly...
So the ultimate question is: is there any use for an unsigned int (uint
)? Even Microsoft seems not to use them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为这也可能与简化较低级别的事情有关,因为如果 Array.Length 是无符号的,并且添加到负整数(二进制补码),那么 Array.Length 在某些时候当然会被添加到负数,可能会出现混乱的结果。
I think it also might have to do with simplifying things on a lower level, since Array.Length will of course be added to a negative number at some point, if Array.Length were unsigned, and added to a negative int (two's complement), there could be messy results.
似乎没有人回答“终极问题”。
我相信无符号整数的主要用途是提供与外部系统(P/Invoke 等)的更轻松的接口,并满足移植到 .NET 的各种语言的需求。
Looks like nobody provided answer to "the ultimate question".
I believe primary use of unsigned ints is to provide easier interfacing with external systems (P/Invoke and the like) and to cover needs of various languages being ported to .NET.
通常,整数值是有符号的,除非您明确需要无符号值。 这只是它们的使用方式。 我可能不同意这个选择,但事实就是如此。
目前,由于当今典型的内存限制,如果您的数组或类似的数据结构需要 UInt32 长度,您应该考虑其他数据结构。
对于字节数组,Int32 将为您提供 2GB 的值
Typically, integer values are signed, unless you explicitly need an unsigned value. It's just the way they are used. I may not agree with that choice, but that's just the way it is.
For the time being, with todays typical memory constraints, if your array or similar data structure needs an UInt32 length, you should consider other data structures.
With an array of bytes, Int32 will give you 2GB of values
Unsigned int 不符合 CLS,因此会将该属性的使用限制为那些实现
UInt
的语言。参见这里:
框架1.1
Framework 2.0
Unsigned int isn't CLS compliant and would therefore restrict usage of the property to those languages that do implement a
UInt
.See here:
Framework 1.1
Framework 2.0
原因有很多:
Many reasons: