如何使用单行代码将多个项目添加到组合框?

How to add multiple items to a combobox using single line of code?

如何使用一行代码将多个项目添加到组合框?

public Form1()
    {
        InitializeComponent();
        comboBox1.Items.Add("simple");
        comboBox1.Items.Add("continuous");
        comboBox1.Items.Add("perfect");
        comboBox1.Items.Add("perfect continuous");
    }

没有理由按照您的要求去做。不必要地减少代码行 (LOC) 是糟糕的编程习惯,应该避免。仅在有意义并改进代码 readability/understanding 的地方执行此操作。

当您使用一种编译语言(C# 被编译成一种中间语言)时,真的没有理由关心您的源文件可以有多小,除非它当然是一种改进。当您处理大小可能很重要的脚本语言时(例如客户端代码的 JavaScript ),缩小器或丑化器利用快捷方式来减少尽可能多的空白,以减小文件大小以加快下载速度 - 但那是仅对已发布的代码是必需的 - 在开发中,您可以保持代码的整洁和可读性。

现在,综上所述,您可以通过使用 string 数组和 foreach 循环来 "shorten" 您的代码。

public Form1 {
    InitializeComponent();
    string[] items = new string[] { "simple", "continuous", "perfect", "perfect continuous" };
    foreach (string item in items) {
        comboBox1.Items.Add(item);
    }
}

不像您想要的那样 "one line",但是@OrelEraki 提出了一种单行解决方案,它使用以与此处所示的字符串数组类似的方式创建的 List 对象。您所看到的可能 "shorter" 与您的示例不同,但它不会像您所拥有的那样随着项目的增加而显着增长。

"How to add multiple items to a combobox using single line of code?"

如果您查看 ComboBox.ObjectCollection you'll see that there's a method named AddRange 的文档。 MSDN 将此方法描述为:

Adds an array of items to the list of items for a ComboBox.

所以您正在寻找的单行线是:

c#:

comboBox1.Items.AddRange(new string[] { "simple", "continuous", "perfect", "perfect continuous" });

vb.net:

ComboBox1.Items.AddRange(New String() {"simple", "continuous", "perfect", "perfect continuous"})

解决这个问题的另一种方法是在[设计]选项卡中。您只需要 select 组合框并打开属性,转到 "Data",然后转到 "Items",然后放入这个“(集合)”。现在您访问新的部分并放置您想要的所有项目。