C# 将uint转换为Int32
我正在尝试从C# 将uint转换为Int32,c#,casting,C#,Casting,我正在尝试从MSNdis\u CurrentPacketFilter检索数据,我的代码如下所示: ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT NdisCurrentPacketFilter FROM MSNdis_CurrentPacketFilter"); foreach (ManagementObject queryObj in s
MSNdis\u 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[“ndiscurrentpackketfilter”]
对象,在本例中是
,uint
的值ndiscurrentpackketfilter
- 已装箱的值类型不能被解装箱到同一类型中,即您必须至少使用以下内容:
(int)(uint)queryObj[“ndiscurrentpackketfilter”]代码>(即您已经在做的事情的单行版本),或
- ,用于执行强制转换,首先将其解装箱到
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
没问题。当我试图找出新列表{1,2,3}.Cast().ToList()的原因时,我找到了这个问题的答案抛出一个
InvalidCastException
——结果是在幕后使用非泛型可枚举的接口对集合进行迭代,该接口将int
值装箱。