【问题标题】:How to "out" an array of strings and pass it through into a listbox如何“输出”字符串数组并将其传递到列表框中
【发布时间】:2011-12-31 05:22:27
【问题描述】:

这是 UpdateGUI() 的一部分:

DisplayOptions choice = (DisplayOptions)comboBox1.SelectedIndex;
seatMngr.GetSeatInfoStrings(choice, out strSeatInfoStrings);
listBox1.Items.Clear();
listBox1.Items.AddRange(strSeatInfoStrings);

编译器在抱怨这一行(以及最后一行的参数):

seatMngr.GetSeatInfoStrings(choice, out strSeatInfoStrings);

我要做的是获取一个数组 (strSeatInfoStrings) 并将其放入一个列表框中。

有什么想法吗?

【问题讨论】:

  • 您是否有任何特殊原因需要使用out 而不仅仅是从方法中返回数组?
  • 你从编译器得到什么错误信息?
  • 是的,我需要用out...我得到的错误信息是:#1"当前上下文中不存在名称'strSeatInfoStrings'"#2"匹配'的最佳重载方法Assignment3.SeatManager.GetSeatInfoStrings(Assignment3.DisplayOptions, out string[])' has some invalid arguments" #3"参数 2:无法从 'out strSeatInfoStrings' 转换为 'out string[]'"

标签: c# arrays listbox out


【解决方案1】:

您必须在调用之前添加该变量的声明:

DisplayOptions choice = (DisplayOptions)comboBox1.SelectedIndex;
string[] strSeatInfoStrings;
seatMngr.GetSeatInfoStrings(choice, out strSeatInfoStrings); 
listBox1.Items.Clear(); 
listBox1.Items.AddRange(strSeatInfoStrings); 

另一种意见是改变你的方法的签名并返回值,所以你可以这样写

DisplayOptions choice = (DisplayOptions)comboBox1.SelectedIndex;
listBox1.Items.Clear(); 
listBox1.Items.AddRange(seatMngr.GetSeatInfoStrings(choice)); 

【讨论】:

  • 我已经清除了“string[] strSeatInfoStrings;”在 seatMngr 对象内的 GetSeatInfoStrings 方法中。当我尝试第一个建议时,我得到“Nullreferenceexception 未处理”,第二个建议让我得到“错误 1 ​​最佳重载方法匹配 'System.Windows.Forms.ListBox.ObjectCollection.AddRange(System.Windows.Forms.ListBox.ObjectCollection )' 有一些无效参数 C:\Users\Kalle\Desktop\Assignment4-hjälp\Assignment4\Assignment3\MainForm.cs 153 13 Assignment4" 还有一些其他问题..
  • 如果您在方法GetSeatInfoStrings 中声明它,那么这是错误的范围。按照我在上面的示例中向您展示的方式声明它,只需在您的方法 GetSetInfoStrings 中使用 out 参数,您就会看到 - 它有效。
  • 我做了,它给了我以下两个错误 #1“使用未分配的输出参数'strSeatInfoStrings'”#2“必须在控制离开当前方法之前分配输出参数'strSeatInfoStrings'”
  • 您必须在离开方法范围之前设置 out 参数的值。所以如果有一个 if 语句,而你只在那里设置了 out 参数,你也必须在 else 部分初始化它。
【解决方案2】:

这听起来更像是代码设计问题。方法名GetSeatInfoStrings 明确表示它返回一些字符串。根据您对该方法的使用,它看起来像这样声明:

public void GetSeatInfoStrings(string choice, out string[] result)

在我看来,这样声明会更好:

public void IEnumerable<string> GetSeatInfoStrings(string choice)

...然后像往常一样从方法中返回数组。 out 的主要用途是当您需要从方法中返回多个值时。 Int32.TryParse 方法就是一个很好的例子;该方法返回一个bool表示成功,out参数将包含结果。

在您的情况下,您似乎只有一个结果,因此使用 out 只会令人困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2014-01-16
    • 2022-01-13
    相关资源
    最近更新 更多