将 uint 转换为 Int32

Cast uint to Int32

我正在尝试从 MSNdis_CurrentPacketFilter 检索数据,我的代码如下所示:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\WMI",
                "SELECT NdisCurrentPacketFilter FROM MSNdis_CurrentPacketFilter");

foreach (ManagementObject queryObj in searcher.Get())
{
     uint obj = (uint)queryObj["NdisCurrentPacketFilter"];
     Int32 i32 = (Int32)obj;
}

如您所见,我从 NdisCurrentPacketFilter 两次 转换接收到的对象,这引出了一个问题:为什么??

如果我尝试将其直接转换为 int,例如:

Int32 i32 = (Int32)queryObj["NdisCurrentPacketFilter"];

它抛出一个 InvalidCastException。这是为什么?

三件事导致这对你不起作用:

  • 根据this link.

  • NdisCurrentPacketFilter的类型是uint
  • 使用索引器queryObj["NdisCurrentPacketFilter"]returns an object, which in this case is a boxeduintNdisCurrentPacketFilter.

  • 的值
  • 盒装值类型 can only 被取消装箱为同一类型,即您 必须 至少使用类似的东西:

    • (int)(uint)queryObj["NdisCurrentPacketFilter"];(即你已经在做的单行版本),或

    • Convert.ToInt32, which uses IConvertible 执行转换,首先将其拆箱到 uint


您可以使用类似

的方法重现与您的问题相同的问题
object obj = (uint)12345;
uint unboxedToUint = (uint)obj; // this is fine as we're unboxing to the same type
int unboxedToInt = (int)obj; // this is not fine since the type of the boxed reference type doesn't match the type you're trying to unbox it into
int convertedToInt = Convert.ToInt32(obj); // this is fine