C# – 错误“并非所有代码路径都返回一个值”,数组作为out参数

我目前有以下代码:

public int GetSeatInfoString(DisplayOptions choice,out string [] strSeatInfoStrings)

{ strSeatInfoStrings = null; int count = GetNumOfSeats(choice); if ((count <= 0)) return 0; strSeatInfoStrings = new string[count]; int i = 0; for (int index = 0; index <= m_totNumOfSeats - 1; index++) { if (string.IsNullOrEmpty(m_nameList[index])) strSeatInfoStrings[i++] = 

m_nameList [索引]的ToString(); }

  } 

此代码产生错误,“… GetSeatInfoString.DisplayOptions,out string [])’:并非所有代码路径都返回一个值。基本上,我在上面的方法中要做的是循环一个数组并为数组中包含字符串的任何值,我想要这些然后添加到新数组strSeatInfoStrings,而strSeatInfoStrings又可以从一个单独的类中调用,然后新的数组内容显示在列表框中。

有关如何纠正此问题的任何建议?

提前致谢

您可以在末尾添加返回strSeatInfoStrings.Length

 public int GetSeatInfoString(DisplayOptions choice, out string[] strSeatInfoStrings) { strSeatInfoStrings = null; int count = GetNumOfSeats(choice); if ((count <= 0)) return 0; strSeatInfoStrings = new string[count]; int i = 0; for (int index = 0; index <= m_totNumOfSeats - 1; index++) { if (string.IsNullOrEmpty(m_nameList[index])) strSeatInfoStrings[i++] = m_nameList[index].ToString(); } return strSeatInfoStrings.Length; } 

在方法退出之前,您没有最终返回。 如果没有元素但您需要在结尾处返回,则表示您正在退出。 如果您对该值不感兴趣,那么为什么不将返回类型设置为void?

您需要根据方法签名返回一个整数值。

在for循环之后应该返回一个值。

该错误与您的out参数无关。

你的方法

 public int GetSeatInfoString( DisplayOptions choice, out string[] strSeatInfoStrings) 

声明为返回一个int ,并不对所有代码路径执行此操作。

如果count <= 0,则只返回一个值。您需要在for循环后返回一个值,或者将方法签名更改为void,具体取决于您希望返回值表示的内容。

如果要返回带有计数的数组,则将返回类型更改为string []并删除out参数。

您想从此function返回什么值? 我想你需要在最后加上这一行:

回归我;