gpt4 book ai didi

c# - 将 uint 转换为 Int32

转载 作者:太空狗 更新时间:2023-10-30 00:18:50 24 4
gpt4 key购买 nike

我正在尝试从 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,根据this link .

  • 使用索引器queryObj["NdisCurrentPacketFilter"] returns一个 object,在本例中是一个 boxed uintNdisCurrentPacketFilter的值。

  • 盒装值类型 can only被拆箱成相同的类型,即你必须至少使用类似的东西:

    • (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

关于c# - 将 uint 转换为 Int32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28928393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com