gpt4 book ai didi

c# - 为什么 Stream.Write 不采用 UInt?

转载 作者:可可西里 更新时间:2023-11-01 08:18:00 26 4
gpt4 key购买 nike

Stream.Write 对我来说似乎非常不合逻辑使用 int,而不是 UInt...对于这个事实,除了“遗留”代码之外还有其他解释吗?有人想写 -1 字节吗?!?

最佳答案

无符号类型不符合 CLS,因此 Stream.Write 不使用 uint 进行偏移和计数。

参见:uint (C# Reference)

The uint type is not CLS-compliant. Use int whenever possible.

有一篇旧文:Why we don't have unsigned types in the CLS by Brad Abrams (2 Sep 2003)这解释了原因:

However there is one issue that keeps coming up: Why did we not allow unsigned types (UInt32 and the like) in the CLS?

Well, there are really two answers to this question. At the first level some languages (such as VB.NET) do not offer full support for unsigned types. For example you can’t have unsigned literals in VB.NET…. But to be fair that is not a completely satisfying answer because when we started the CLS you could not subclass in VB.NET either, but we extended that language to support what we knew people would want. We could have done the same thing with unsigned types. But we didn’t. Why not? Well, that gets a deeper reason. In fact the same reason why early betas of the C# language did not support unsigned types (no ushort, uint and the like).

The general feeling among many of us is that the vast majority of programming is done with signed types. Whenever you switch to unsigned types you force a mental model switch (and an ugly cast). In the worst cast you build up a whole parallel world of APIs that take unsigned types. The value of avoiding the “< 0” check is not worth the inclusion of generics in the CLS.

(请注意,较新版本的 VB.Net(VB 8 及更高版本)支持无符号类型)

还有一件事(可能不相关)要补充,Stream.Write implementation检查负值:

[System.Security.SecuritySafeCritical]  // auto-generated
public override void Write(byte[] array, int offset, int count) {
if (array==null)
throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));

关于c# - 为什么 Stream.Write 不采用 UInt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30580324/

26 4 0