简体   繁体   中英

Unable to cast object of type 'System.Byte' to type 'System.UInt64'

Is byte convertible to 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'.'

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?

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:

The source sequence for this method is IEnumerable, which means the elements have the compile-time static type of object. 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. 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.

You have to use Select to perform the cast:

ulong[] ip = HttpContext.Connection.RemoteIpAddress.GetAddressBytes()
              .Select(x => (ulong)x).ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM