Which is better, return value or out parameter? Ask Question

Which is better, return value or out parameter? Ask Question

If we want to get a value from a method, we can use either return value, like this:

public int GetValue(); 

or:

public void GetValue(out int x);

I don't really understand the differences between them, and so, don't know which is better. Could you explain this to me?

ベストアンサー1

Return values are almost always the right choice when the method doesn't have anything else to return. (In fact, I can't think of any cases where I'd ever want a void method with an out parameter, if I had the choice. C# 7's Deconstruct methods for language-supported deconstruction acts as a very, very rare exception to this rule.)

他の点とは別に、呼び出し側が変数を個別に宣言する必要がなくなります。

int foo;
GetValue(out foo);

int foo = GetValue();

Out 値は次のようなメソッドの連鎖も防止します。

Console.WriteLine(GetValue().ToString("g"));

(実際、これはプロパティ セッターの問題の 1 つでもあり、ビルダー パターンがビルダーを返すメソッドを使用するのはそのためですmyStringBuilder.Append(xxx).Append(yyy)。)

さらに、出力パラメータはリフレクションで使用するのが少し難しく、通常はテストも難しくなります。(通常、出力パラメータよりも戻り値のモックを簡単にするために多くの労力が費やされます)。基本的に、それらによって何が変わるかは思いつきません。より簡単に...

戻り値は最高です。

編集: 何が起こっているかと言うと...

基本的に「出力」パラメータに引数を渡すときは、持っている変数を渡します。(配列要素も変数として分類されます。) 呼び出すメソッドには、パラメータ用のスタックに「新しい」変数がありません。変数はストレージとして使用されます。変数の変更はすぐに表示されます。違いを示す例を次に示します。

using System;

class Test
{
    static int value;

    static void ShowValue(string description)
    {
        Console.WriteLine(description + value);
    }

    static void Main()
    {
        Console.WriteLine("Return value test...");
        value = 5;
        value = ReturnValue();
        ShowValue("Value after ReturnValue(): ");

        value = 5;
        Console.WriteLine("Out parameter test...");
        OutParameter(out value);
        ShowValue("Value after OutParameter(): ");
    }

    static int ReturnValue()
    {
        ShowValue("ReturnValue (pre): ");
        int tmp = 10;
        ShowValue("ReturnValue (post): ");
        return tmp;
    }

    static void OutParameter(out int tmp)
    {
        ShowValue("OutParameter (pre): ");
        tmp = 10;
        ShowValue("OutParameter (post): ");
    }
}

結果:

Return value test...
ReturnValue (pre): 5
ReturnValue (post): 5
Value after ReturnValue(): 10
Out parameter test...
OutParameter (pre): 5
OutParameter (post): 10
Value after OutParameter(): 10

違いは「後」ステップ、つまりローカル変数またはパラメータが変更された後にあります。ReturnValueテストでは、これは静的value変数には影響しません。OutParameterテストでは、value変数は次の行で変更されます。tmp = 10;

おすすめ記事