Why does .NET Framework not use unsigned data type

2019-01-09 11:57发布

问题:

Possible Duplicate:
Why is Array.Length an int, and not an uint

Is there is a reason behind it .NET Framework not using unsigned data types?

Shouldn't I be adopting them in my code, but for example, the Count property of a List<> is an int. You can't have a negative count, so why shouldn't it be defined as a uint? Should I use only int's even though I know the count can not be negative?

回答1:

Unsigned numeric types are not CLS compliant so they should not be used for any API - especially the .NET framework.

Basically, CLS compliant code only utilizes types that are available in all .NET languages. Some languages (like VB.NET) does not support unsigned numeric types.



回答2:

The most basic answer is that the .NET framework designers chose to have signed integers part of the BCL (base class library) and CLS (common language syntax) specification, whereas they did not chose to make unsigned integers part of it.

For the reasoning behind that decision, ultimately you'd have to ask Microsoft. I would imagine that Eric Lippert could chime in here with a more thorough explanation.

It comes down to the following facts:

  • You can't (or at least don't) have an implicit conversion between int and uint, meaning that conversions must be made explicitly using cast syntax
  • It's best to avoid unnecessary casting syntax if it isn't adding to the readability of the code
  • The upper bounds of int is sufficient for most numbers that we deal with in code

Putting those together means that the int type serves the purpose in most cases.



回答3:

Unsigned numbers are not CLS compliant because there are languages that do not support those types. I speak under correction, but VB.NET does not support unsigned types. This means that if you declare an public member as an unsigned type, then your assembly cannot be used from VB.NET or any other .NET language that does not support unsigned types.



回答4:

Some .NET aware languages do allow unsigned ints. E.g. in C# you can use uint.

However, as they not CLS compliant if you expose them outside of your assembly then you might find that other developers using a different language will have problems using your classes.

So in summary... Feel free to use them, but keep them zipped up inside your classes using either the private or internal keywords.