将 uint 转换为 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.为什么?

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

  • NdisCurrentPacketFilter的类型是 uint ,根据此链接。

  • 使用索引器queryObj["NdisCurrentPacketFilter"]返回一个object,在本例中为盒装uint,值为NdisCurrentPacketFilter

  • 装箱
  • 值类型只能取消装箱为同一类型,即您至少必须使用以下内容:

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

    • Convert.ToInt32 ,它使用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

最新更新