网络接口列表、抽象类型或接口

Dus*_*san 0 c# winforms network-interface

我有一个程序列出了硬盘驱动器和网络接口,如下图所示: 网络接口列表

如果我单击硬盘名称,我可以在文本框中看到驱动器类型。这工作正常。但是,如果我在网络接口上尝试此代码,它不起作用。它给出了错误 CS0144:无法创建抽象类型或接口“NetworkInterface”的实例

这是代码:

 private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            textBox1.Text = "";
            DriveInfo[] Drives = DriveInfo.GetDrives();
            foreach (DriveInfo drv in Drives)
            {
                listBox1.Items.Add(drv.Name);
            }
        }
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            String strDrive = (string)listBox1.SelectedItem;
            DriveInfo drive = new DriveInfo(strDrive);

            textBox1.Text = drive.DriveType.ToString();
        }
Run Code Online (Sandbox Code Playgroud)

这里是不工作的网络接口:

private void button3_Click(object sender, EventArgs e)
        {
            listBox2.Items.Clear();
            textBox2.Text = "";
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                listBox2.Items.Add(adapter.Name);
            }
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            String strInterface = (string)listBox2.SelectedItem;
            NetworkInterface adapter = new NetworkInterface(strInterface);
            textBox2.Text = adapter.Description.ToString();
        }
Run Code Online (Sandbox Code Playgroud)

这行是错误的: NetworkInterface 适配器 = new NetworkInterface(strInterface);

Gur*_*ron 5

来自NetworkInterface文档

您不创建此类的实例;该GetAllNetworkInterfaces方法返回一个数组,其中包含本地计算机上每个网络接口的此类的一个实例。

所以你可以GetAllNetworkInterfaces再次调用并过滤结果:

var adapter = NetworkInterface.GetAllNetworkInterfaces()
    .FirstOrDefault(ni => ni.Name == strInterface);
// if not null ...
Run Code Online (Sandbox Code Playgroud)

或者将先前调用的结果存储在某个字段/属性中并使用它们进行搜索。或者只是使用结果数组作为listBox2其本身的数据源。