为什么我不能从 System.Object 中提取 ushort,然后将其转换为 uint? (C#)
我正在操作 System.Management.ManagementObjectCollection
列表中的项目。 其中每一项都是一个 System.Management.ManagementObject
,其中包含按字符串索引的属性。 请参阅:
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"];
...
...
...
}
对 queryObj
的每个“字典访问”都会返回一个 C# object
,它实际上是属性应该是什么 - 我必须事先知道它们的“真实”类型,没关系。
问题是,我在 uint
转换中收到 InvalidCastException
。 我必须使用真实类型,即ushort
。 从 ushort
到 uint
的转换不应该是可以接受和明显的吗?
在这种情况下,我最终会将这些值转换为 string
,但是如果我必须将它们转换为 uint
或 int
或 该怎么办? >长
变量?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在尝试对 ushort 进行拆箱,但它只能拆箱为 ushort。
拆箱后,您就可以像平常一样投射它。
任何 T 类型的装箱值只能拆箱为 T(或 Nullable)。
Eric Lippert 就此事发表了一篇非常好的博客文章 这里。
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.
强制转换运算符的问题在于它实际上意味着两件事:强制转换和转换。 您可以将值从数字转换为不同的数字,但不能将盒装数字转换为错误类型的数字。 因此,你必须做的是:
更好的是:
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:
Better yet: