Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将uint转换为Int32_C#_Casting - Fatal编程技术网

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
值装箱。