我试图从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。为什么会这样呢?
发布于 2015-03-08 14:05:34
造成这种情况的原因有三:
NdisCurrentPacketFilter的类型是uint,根据this link的说法。queryObj["NdisCurrentPacketFilter"] returns an object,在本例中是boxed uint,它是NdisCurrentPacketFilter的值。- `(int)(uint)queryObj["NdisCurrentPacketFilter"];` (i.e. a single-line version of what you're already doing), or
- [`Convert.ToInt32`](http://msdn.microsoft.com/en-us/library/23511zys), which uses [`IConvertible`](http://msdn.microsoft.com/en-us/library/system.iconvertible) to perform the cast, unboxing it to `uint` first.
你可以用这样的方法重复你问题中的相同问题
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 finehttps://stackoverflow.com/questions/28928393
复制相似问题