[英]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.