C#数组和列表

C#数组和列表,c#,C#,我想将列表框中的项目添加到字符串数组中 然而,当我运行代码时,我在变量声明上得到一个空引用异常。有什么想法吗 清单项目; 字符串[]数组 public MainWindow() { InitializeComponent(); items = new List<String>(); listBox.Items.Add("Kevin"); listBox.Items.Add("James");

我想将列表框中的项目添加到字符串数组中

然而,当我运行代码时,我在变量声明上得到一个空引用异常。有什么想法吗

清单项目; 字符串[]数组

    public MainWindow()
    {
        InitializeComponent();

        items = new List<String>();
        listBox.Items.Add("Kevin");
        listBox.Items.Add("James");
        listBox.Items.Add("John");
        listBox.Items.Add("Mathew");
        listBox.Items.Add("George");
public主窗口()
{
初始化组件();
项目=新列表();
listBox.Items.Add(“Kevin”);
listBox.Items.Add(“James”);
listBox.Items.Add(“John”);
listBox.Items.Add(“Mathew”);
列表框。项目。添加(“乔治”);

您需要初始化数组,您仅将其声明为类的成员:

private void Button_Click_2(object sender, RoutedEventArgs e)
{
    array = new string[listbox.Items.Count];

    ExchangeSort(array);
    listBox.Items.Clear();
    foreach (string i in array)
    {
        listBox.Items.Add(i);
    }
    MessageBox.Show("Done");

}

更容易使用C#丰富的数据类型。List、Dictionary和SortedList等。是否传递空数组?什么方法调用ExchangeSort()?您是否尝试调试代码?根据您的错误,数组输入参数为null,因此它不是由调用方法发送的。如何调用该方法?似乎传入了null值。此外,为什么不使用
数组。排序
或类似方法?我收到错误消息:错误1'System.Windows.Controls.ItemCollection'not包含“Length”的定义,并且找不到接受类型为“System.Windows.Controls.ItemCollection”的第一个参数的扩展方法“Length”(是否缺少using指令或程序集引用?)。抱歉,这是计数,不是长度