【发布时间】:2016-12-05 21:58:12
【问题描述】:
在 C# 中,在有符号和无符号整数类型之间进行转换的能力似乎受到以下因素的影响:
- 是否正在转换标量或数组类型。
- 变量是否声明为
object。
考虑以下代码示例:
// If the variable is declared as a byte array then type casting to sbyte[] results in a
// compile-time error.
byte[] byteArray = new byte[2];
var c = (sbyte[])byteArray; // Compilation eror
// But if the variable is declared as an object then we neither get a compile-time nor a
// run-time error
object byteArrayObject = new byte[2];
var a = (sbyte[])byteArrayObject;
// With an explicitly typed scalar, the byte -> sbyte type conversion succeeds with no errors
byte scalarByte = 255;
var b = (sbyte)scalarByte;
// But if the scalar is declared as an object, an InvalidCastException is thrown at run-time
object byteObject = (byte)4;
var e = (sbyte)byteObject; // InvalidCastException
总结一下:
- 数组声明为字节[]:失败
- 数组声明为对象:成功
- 标量声明为字节:成功
- 标量声明为对象:失败
虽然此示例仅考虑字节,但相同的模式似乎适用于其他整数类型。谁能解释为什么这些结果如此不一致?
【问题讨论】:
-
此链接提供第一部分的答案(关于数组):stackoverflow.com/a/33896378/5311735。这到第二个:blogs.msdn.microsoft.com/ericlippert/2009/03/19/…
-
只有第二个例子搞砸了,imo。数组不应该是协变的,但它们是:stackoverflow.com/questions/4317459
-
您的问题的一个更好的标题是“当涉及数组时,C# 中的显式转换如何工作,涉及装箱时它如何工作”?这是两个问题,有符号整数与无符号整数完全无关。