为什么我不能从System.Object中提取一个ushort,然后将它作为一个uint? (C#) [英] Why can't I pull a ushort from a System.Object and then cast it as a uint? (C#)
问题描述
我正在操作 System.Management.ManagementObjectCollection
的列表中的项目。每个项目都是一个 System.Management.ManagementObject
,其中包含以字符串索引的属性。请参阅:
foreach(searchObject中的ManagementObject queryObj)
{
string osversion = string)queryObj [Version];
string os =(string)queryObj [Name];
uint spmajor =(uint)queryObj [ServicePackMajorVersion];
uint spminor =(uint)queryObj [ServicePackMinorVersion];
...
...
...
}
每个字典访问queryObj
返回一个C#对象
问题是,我得到一个 InvalidCastException
uint
中强制转换。我必须使用真正的类型,这是 ushort
。从 ushort
到 uint
的演员不应该可以接受吗? 在这种情况下,我最终会将值转换为 string
,但如果我不得不将它们转换为 uint
或
int
或 long
变量?
您正尝试取消包装,而且只能取消装箱到某个群组。
任何类型为T的盒装值只能被取消装箱为T(或Nullable) 。
Eric Lippert对这个确切的事情做了非常好的博客文章此处。
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?
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.
这篇关于为什么我不能从System.Object中提取一个ushort,然后将它作为一个uint? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!