Why can't I pull a ushort from a System.Object and then cast it as a uint? (C#)

南笙酒味 提交于 2019-12-23 20:32:09

问题


I'm manipulating the items in a list that's a System.Management.ManagementObjectCollection. Each of these items is a System.Management.ManagementObject which contains properties indexed by string. See:

foreach (ManagementObject queryObj in searcher.Get())
{
    string osversion = (string)queryObj["Version"];
    string os = (string)queryObj["Name"];
    uint spmajor = (uint)queryObj["ServicePackMajorVersion"];
    uint spminor = (uint)queryObj["ServicePackMinorVersion"];
    ...
    ...
    ...
}

Each "dictionary access" to queryObj returns a C# object which is in fact whatever the property is supposed to be -- I have to know their "real" type beforehand, and that's OK.

Problem is, I get a InvalidCastException in the uint casts. I have to use the real type, which is ushort. Shouldn't a cast from ushort to uint be acceptable and obvious?

In this case, I'll eventually convert the values to string, but what if I had to get them into uint or int or long variables?


回答1:


You're attempting to unbox a ushort, and it can only be unboxed to a ushort.

Once you've unboxed it you can then cast it as normal.

Any boxed value of type T can only be unboxed to a T (or a Nullable).

Eric Lippert did a very good blog post about this exact thing here.




回答2:


The problem with the casting operator is it really means two things: cast and convert. You can convert a value from a number to a different number, but you cannot cast a boxed number to the wrong type of number. Thus, what you'd have to do instead is:

uint spmajor = (uint)(ushort)queryObj["ServicePackMajorVersion"];

Better yet:

uint spmajor = Convert.ToUInt32(queryObj["ServicePackMajorVersion"]);


来源:https://stackoverflow.com/questions/1080945/why-cant-i-pull-a-ushort-from-a-system-object-and-then-cast-it-as-a-uint-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!