我有代码,它使用System.Net和System.Net.NetworkInformation引用,它生成一个我的网络连接名称列表.
一切似乎都很好并且正常工作,但是当我创建了一个这样的代码,并将导出的值导出到listBox1项添加时,我只有一个网络连接名称,但实际上我有四个.
我怎么解决这个问题?
private void button1_Click(object sender,EventArgs e) { Adapters obj = new Adapters(); var value = obj.net_adapters(); listBox1.Items.Add(value); } public class Adapters { public string net_adapters() { string value = string.Empty; foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { value = nic.Name; } return value; } }
解决方法
我会修改你目前的代码:
public string net_adapters() { string value = string.Empty; foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { // bug in your original code right here is `=` // you proably meant to do something like value += "," + nic.Name // which would not work well with listBox Items collection value = nic.Name; } return value; }
这样:
public System.Collections.Generic.List<String> net_adapters() { List<String> values = new List<String>(); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { values.Add(nic.Name); } return values; }
一种更奇特的方式(虽然它可能无关紧要,因为GetAllNetworkIntefaces可能阻塞,直到它有一个完整列表)将使用IEnumerable< T>和收益率:
public IEnumerable<String> net_adapters() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { yield return nic.Name; } yield break; }
不管怎样,你会像这样使用它:
var obj = new Adapters(); var values = obj.net_adapters(); listBox1.ItemsSource = values;
(另外,我建议您使用.NET Framework Naming Guide)