C# 在while循环中返回字符串

C# 在while循环中返回字符串,c#,C#,我试过谷歌,还有这里的高级搜索。不走运 Class SomeClass { public string MethodName() { //Some Code While(conditions) { //More Code string X; X = "string stuff"; return X; } } } 我得到一

我试过谷歌,还有这里的高级搜索。不走运

Class SomeClass
{
    public string MethodName()
    {
    //Some Code
        While(conditions)
        {
            //More Code
            string X;
            X = "string stuff";
            return X;
        }
    }
}

我得到一个“并非所有代码路径都返回值”错误。我相信我可以解决这个问题,但我想知道如何解决这个问题,以供将来参考。

问题是编译器认为有一条路径在第一次到达时不满足条件,而:

//Some Code
while(conditions)
{
  //More Code
  string X;
  X = "string stuff";
  return X;
}
.. Problem!
return "not found"; // or throw new Exception("I'm not supposed to be here")

你需要做的是还回或扔!在完全不满足条件的情况下

出现错误是因为您试图从while循环返回值,这是不可能的

如果您的while循环条件不满足而不是no value get return,那么这里的问题就是编译器给您错误的原因

解决方法是,在函数返回值的循环外部返回空字符串

public string functionname
{
    while(conditions)
    {
      //More Code
      string X;
      X = "string stuff";
      return X;
    }
    return string.Empty;
}
想一想,如果while循环条件不满足,您的方法会返回字符串吗?所以将返回放在方法末尾之前,以确保方法始终返回字符串,此MSDN错误页将进一步帮助您理解

我相信示例代码只是为了说明问题,因为它对我来说没有多大意义

public string MethodName() 
{
    //Some Code
    While(conditions) {
        //More Code
        string X;
        X = "string stuff";
        return X;
    }
    return "somestringifnotX";
}

您的问题是,如果不通过while循环,您将不会返回任何内容

Class SomeClass
{
  public string MethodName()
  {
    //Some Code
    While(conditions)
    {
      //More Code
      string X;
      X = "string stuff";
      return X;
    }
    return "Nothing to return Actually";
    //OR
    Throw new Exception("Conditions where false");
  }
}
假设您的条件为false,并且您从未输入while。这意味着你将永远无法返回。另一方面,您的函数需要一个。当您不希望出现这种行为时,以返回或抛出错误结束您的语句。

我想您是认真的

 static void Main(string[] args)
    {

        for (int i = 0; i < MethodName().Count; i++ )
        {
            var result = MethodName()[i] as string;
            Console.WriteLine(result);
        }

        Console.ReadLine();
    }

    private static List<string> MethodName()
    {
        var items = new List<string>();

        while (Condition)
        {
            items.Add("SString to return");
        }

        return items;
    }

我希望这会有帮助

如果你的条件是错误的怎么办?在这种情况下,您的方法不会返回任何内容,但编译器无法知道它的值。您需要在方法末尾添加一个返回。while循环可能返回字符串,但该方法不返回;然后阅读此类错误的原因,稍微考虑一下,然后按照一些建议修复代码。如果之后仍然存在问题,请询问它:确保以某种方式区分它。从while循环返回很好。@StuartLC-从while循环返回很好,但是如果while循环条件不满足,那么我们需要返回一些已取消的值,如我所指的空字符串。。。
public static string binarySearch(int [] dataArray, int dataDicari) 
{
      int first = 0;
      int last = list.length – 1;
      int mid;       

      while (first <= last)
      {
          mid = (first+last)/2;
          if (dataArray[mid] == dataDicari)
              return ......;               //ISIAN 1                        
          else if (dataArray[mid] < dataDicari) 
              first = mid + 1;
          else if (dataArray[mid] > dataDicari) 
              last = mid – 1;
      }

      return .....;    //ISIAN 2
}