簡體   English   中英

將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 這是為什么?

有三件事對你不起作用:

  • 根據此鏈接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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM