为什么我不能拉USHORT从一个System.Object,然后将它转换为uint? (C#) [英] Why can't I pull a ushort from a System.Object and then cast it as a uint? (C#)

查看:380
本文介绍了为什么我不能拉USHORT从一个System.Object,然后将它转换为uint? (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我操纵在列表中的项目,这是一个 System.Management.ManagementObjectCollection 。每个项目都是一个 System.Management.ManagementObject 其中包含字符串索引属性。参见:

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"];
    ...
    ...
    ...
}

每个字典访问 queryObj 返回一个C#对象这实际上无论属性是应该是 - 我得事先知道他们的真正的类型,这是确定

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.

问题是,我收到了 InvalidCastException的 UINT 转换。我必须使用真实的类型,它是 USHORT 。不应该从 USHORT 强制转换为 UINT 是可以接受的和明显的?

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?

在这种情况下,我会最终值转换为字符串,但如果我不得不让他们进入 UINT INT 变量?

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?

推荐答案

您正试图拆箱 USHORT,它只能是拆箱到USHORT。

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.

T类型的任何装箱值只能是拆箱到T(或可空)

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

埃里克利珀做了很好的博客文章这个确切的事情的here

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

这篇关于为什么我不能拉USHORT从一个System.Object,然后将它转换为uint? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆