Skip to main content
 首页 » 编程设计

c#之使用 foreach 循环从 System.String[] 打印值

2024年02月13日12qq号

我的目标是获取 IP 地址和 NIC 名称, 这是我的示例代码,我想获取类型为 System.String[] 的 IPAddress 对象的值,我看到很多互联网帖子并尝试复制他们的代码以获得 >foreach 循环,但它对我不起作用,可能是什么问题?

我还在习惯 foreach 循环,因为这周它对我来说是新的

我的错误在 foreach 错误中突出显示:

foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration "); 
 
int ram = 1; 
foreach (ManagementObject obj in searcher.Get()) 
{ 
     if (obj["MACAddress"] != null) 
     { 
         Console.WriteLine(String.Format("NIC #{0}:", ram)); 
 
         if (obj["IPAddress"] != null) // IPAddress is of type System.String[] 
         { 
             foreach (string s in obj["IPAddress"]) 
             {  
                 Console.WriteLine(s);          
             }    
         } 
     } 
} 

请您参考如下方法:

此错误告诉您 obj["IPAddress"] 正在返回一个 object 而 foreach 不知道如何迭代通过一个对象。

因此,您必须首先将obj 转换为可迭代集合:

 String[] addresses = (String[])obj["IPAddress"]; 
 foreach (string s in addresses) 
 {  
     Console.WriteLine(s);          
 } 

取自msdn documentation :

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface.

因此 foreach 不支持 object 类型。