[英]Unable to cast object of type 'System.Byte' to type 'System.UInt64'
Is byte
convertible to ulong
? byte
转换为ulong
吗?
It would seem so. 看起来似乎如此。 This doesn't throw:
这不会抛出:
byte wtf = HttpContext.Connection.RemoteIpAddress.GetAddressBytes()[0];
ulong ffs = (ulong)wtf;
OK so let's try to convert the whole array in one: 好的,让我们尝试将整个数组转换为:
ulong[] ip = HttpContext.Connection.RemoteIpAddress.GetAddressBytes().Cast<ulong>().ToArray();
This throws!? 这引发了!?
System.InvalidCastException: 'Unable to cast object of type 'System.Byte' to type 'System.UInt64'.'
System.InvalidCastException:'无法将'System.Byte'类型的对象强制转换为'System.UInt64'。'
Eh? 嗯? Mr. Interpreter, how is it possible you were able to cast
System.Byte
to System.UInt64
when I asked you to do this for variable wtf
, but when I'm asking you to do this for the whole array at once you complain? 解释器先生,当我要求你为变量
wtf
执行此操作时,你怎么可能将System.Byte
为System.UInt64
,但是当我要求你立即为整个阵列执行此操作时,你会抱怨?
In all honesty, what's going on here? 说实话,这里发生了什么? Am I sleepy already and missing something simple?
我已经困了,想念一些简单的东西吗? Could someone kindly explain this to me?
有人可以向我解释这个吗?
The MSDN documentation for Enumerable.Cast<T>
states the following: Enumerable.Cast<T>
的MSDN文档声明如下:
The source sequence for this method is IEnumerable, which means the elements have the compile-time static type of object.
此方法的源序列是IEnumerable,这意味着元素具有编译时静态类型的对象。 The only type conversions that are performed by this method are reference conversions and unboxing conversions.
此方法执行的唯一类型转换是引用转化和拆箱转换。 The runtime type of the elements in the collection must match the target type, or in the case of value types, the runtime type of elements must be the result of a boxing conversion of the target type.
集合中元素的运行时类型必须与目标类型匹配,或者在值类型的情况下,元素的运行时类型必须是目标类型的装箱转换的结果。 Other conversion types, such as those between different numeric types, are not allowed
不允许使用其他转换类型,例如不同数字类型之间的转换类型
So it is bascially only for casting non-generic collections to make them usable with LINQ. 因此,它只是用于转换非泛型集合以使它们可用于LINQ。 It only works on objects that are already of the destination type during runtime (or boxed), which isn't the case for
byte
and ulong
, what is rather a re-interpretation of the bytes in memory. 它仅适用于在运行时(或盒装)中已经是目标类型的对象,而不是
byte
和ulong
的情况,而是对内存中字节的重新解释。
You have to use Select
to perform the cast: 您必须使用
Select
来执行强制转换:
ulong[] ip = HttpContext.Connection.RemoteIpAddress.GetAddressBytes()
.Select(x => (ulong)x).ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.