将uint转换为Int32

Eli*_*Eli 4 c# casting

我正在尝试从中检索数据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;
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我正在从NdisCurrentPacketFilter 两次投射接收的物体,这引出了一个问题:为什么

如果我尝试将其直接投射到int,例如:

Int32 i32 = (Int32)queryObj["NdisCurrentPacketFilter"];
Run Code Online (Sandbox Code Playgroud)

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

Wai*_*Lee 10

有三件事对你不起作用:

  • 根据这个链接,类型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
Run Code Online (Sandbox Code Playgroud)