0

おはようございます、単純なばかげた質問です。同様の問題がある投稿を見つけましたが、読んでもエラーは解決しません。

For ループからの戻り値

メソッド内の foreach ループから戻り値を取得できません

メソッド: 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;
    }

}
}
4

3 に答える 3

3

メソッドは文字列を返す必要があると言っていますが、i<>3 の場合、何を返す必要があるかはわかりません。ちなみに、方法2と3には同じ問題があります(および4も)。メソッド TheInt については説明しませんが、これは... 面白いです ;)

修正

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*/;
}
于 2012-06-28T14:05:55.350 に答える
0

関数は、if が true に評価された場合にのみ戻ります。if の外側に return ステートメントを追加するか、else ステートメントを追加すると、コードがコンパイルされて機能します。

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

    if (0 == (i % 3))
    {
        return f;
    }
    else
      return "";
}
于 2012-06-28T14:06:35.633 に答える
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
} 
于 2012-06-28T14:07:41.213 に答える