2012-06-28 148 views
0

早上,简单的愚蠢的问题。我发现有类似问题的帖子,但通读后并不能解决我的错误。返回值从循环内不显示

Return value from For loop

Can't get a return value from a foreach loop inside a method

的方法:METH1 meth2 ECT ....所有返回一个值,但此刻我正在错误

“错误1“Proj5.Program.meth1 (int)':不是所有的代码路径都会为每个方法返回一个值“。

我的逻辑推测是它没有看到循环内的值? ...

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Proj5 
{ 
class Program 
{ 
    static void Main() 
    { 
     for (int i = 1; i < 101; i++) 
     { 
      if (i == 3 || 0 == (i % 3) || 0 == (i % 5) || i == 5) 
      { 
       Console.Write(meth1(i)); 
       Console.Write(meth2(i)); 
       Console.Write(meth3(i)); 
       Console.Write(meth4(i)); 
      } 
      else 
      { 
       Console.Write(TheInt(i)); 
      } 
     } 
     Console.ReadLine(); 
    } 

    static string meth1(int i) 
    { 
     string f = "fuzz"; 

     if (i == 3) 
     { 
      return f; 
     } 
    } 
    static string meth2(int i) 
    { 
     string f = "fuzz"; 

     if (0 == (i % 3)) 
     { 
      return f; 
     } 
    } 
    static string meth3(int i) 
    { 
     string b = "buzz"; 

     if (i == 5) 
     { 
      return b; 
     } 

    } 
    static string meth4(int i) 
    { 
     string b = "buzz"; 

     if (0 == (i % 5)) 
     { 
      return b; 
     } 
    } 
    static int TheInt(int i) 
    { 
     return i; 
    } 

} 
} 

回答

3

你说你的方法应该返回一个字符串,但如果我<> 3,你不说什么应该返回。方法2和方法3具有相同的问题,顺便说一句(也是4)。 我不会对方法的INT,这是......搞笑说话;)

修正

static string meth1(int i) 
    { 
     string f = "fuzz"; 

     if (i == 3) 
     { 
      return f; 
     } 
     return null;//add a "default" return, null or string.Empty 
    } 

或更短

static string meth1(int i) { 
    return (i == 3) ? "fuzz" : null/*or string.Empty*/; 
} 
+0

你只需给它一个空在它的位置?如果可能的话,我想知道背后的逻辑。 – Dan

+1

返回'string'的方法必须*总是*返回'string'或抛出异常。你的代码不会返回任何东西,除非'if'评估为真。这解决了如果'if'评估为false则返回null。 –

+0

听起来不错,很有道理!感谢您的小凹凸=) – Dan

0

你的函数只返回时,如果被评估为真。在if语句外添加return语句,或添加else语句,并且您的代码将被编译和工作。

static string meth2(int i) 
{ 
    string f = "fuzz"; 

    if (0 == (i % 3)) 
    { 
     return f; 
    } 
    else 
     return ""; 
} 
0

当你声明一个返回值的方法(如meth1等)时,你应该遵守这个声明。

如果内部条件不符合,您的方法不会返回任何内容。 编译器注意到这一点,并与你一起投诉

你应该确保每一个可能的执行路径都将被调用的方法返回给调用者。

例如

static string meth3(int i)  
{   
    string b = "buzz";   
    if (i == 5)   
    {    
     return b;   
    }  
    // What if the code reaches this point? 
    // What do you return to the caller? 
    return string.Empty; // or whatever you decide as correct default for this method 
}