使用uint vs int [英] using uint vs int

查看:97
本文介绍了使用uint vs int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我观察了一段时间,C#程序员倾向于在所有地方使用int,而很少使用uint。但是我从来没有找到一个令人满意的答案。



如果互操作性是您的目标,那么uint不应出现在公共API中,因为并非所有的CLI语言都支持无符号整数。但这并不能解释为什么int如此普遍,即使在内部类中也是如此。我怀疑这是在BCL中很少使用uint的原因。



在C ++中,如果您有一个没有负值的整数,则选择一个无符号整数



这显然表示不允许或预期为负数,编译器将为您做一些检查。我还怀疑在数组索引的情况下,JIT可以轻易删除下限检查。



但是,在混合int和单位类型时,会格外小心和强制转换



应该更多地使用uint吗?为什么?

解决方案

您对为什么不使用 uint 的观察我怀疑BCL是主要原因。



UInt32不符合CLS,这意味着它完全不适合在公共API中使用。如果您要在私有API中使用uint,则意味着要转换为其他类型-保持类型不变通常更容易,更安全。



<我还怀疑即使在仅使用C#语言的情况下,这在C#开发中也不常见,主要是因为它在BCL中并不常见。通常,开发人员会尝试(感谢)模仿他们所构建的框架的样式-在C#的情况下,这意味着尝试使您的API(公共的和内部的)看起来尽可能类似于.NET Framework BCL。这意味着要谨慎使用uint。


I have observed for a while that C# programmers tend to use int everywhere, and rarely resort to uint. But I have never discovered a satisfactory answer as to why.

If interoperability is your goal, uint shouldn't appear in public APIs because not all CLI languages support unsigned integers. But that doesn't explain why int is so prevalent, even in internal classes. I suspect this is the reason uint is used sparingly in the BCL.

In C++, if you have an integer for which negative values make no sense, you choose an unsigned integer.

This clearly signifies that negative numbers are not allowed or expected, and the compiler will do some checking for you. I also suspect in the case of array indices, that the JIT can easily drop the lower bounds check.

However, when mixing int and unit types, extra care and casts will be needed.

Should uint be used more? Why?

解决方案

Your observation of why uint isn't used in the BCL is the main reason, I suspect.

UInt32 is not CLS Compliant, which means that it is wholly inappropriate for use in public APIs. If you're going to be using uint in your private API, this will mean doing conversions to other types - and it's typically easier and safer to just keep the type the same.

I also suspect that this is not as common in C# development, even when C# is the only language being used, primarily because it is not common in the BCL. Developers, in general, try to (thankfully) mimic the style of the framework on which they are building - in C#'s case, this means trying to make your APIs, public and internal, look as much like the .NET Framework BCL as possible. This would mean using uint sparingly.

这篇关于使用uint vs int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆