在控制台应用程序 c# 中使用 out 参数

Using out parameter in the console app c#

我正在使用一个使用 C# 的控制台应用程序,它有一个调用另一个方法并传递输出参数的方法

    public void method1()
    {       
            int trycount = 0;     
            ....
            foreach (var gtin in gtins)
            {
                method2(gtin, out trycount);
            }           

        if (trycount > 5)
        {...}
    }

    public void method2 (string gtin, out int trycount)
    {
      //gives me a compilation error if i don't assign 
      //trycount=0;
        ......  
        trycount++;
    }

我不想覆盖 trycount 变量 = 0,因为在方法 1 中第二次执行 foreach 之后,trycount 有一个值。我想将变量传回,以便在 foreach 之后我可以检查参数的值。

我知道我可以做类似 return trycount = method2(gtin, trycount) 的事情,但如果可能的话,我想尝试使用 out 参数。谢谢

听起来您想要 ref 参数而不是 out 参数。基本上 out 就像有一个额外的 return 值 - 它最初在逻辑上 没有 一个值(它没有明确分配,并且必须在之前明确分配该方法正常退出)。

这也是为什么你不需要必须有一个明确分配的变量才能将其用作参数的原因:

int x;
// x isn't definitely assigned here
MethodWithOut(out x);
// Now it is
Console.WriteLine(x);

逻辑上,当你调用MethodWithOut时,x没有任何值,所以如果方法可以使用这个值,你会选择什么值期待它得到?

将此与 ref 参数进行比较,它是有效的 "in and out" - 您用于参数的变量必须在调用之前明确分配,参数最初是明确分配的,因此您可以从中读取,调用者可以看到在方法中对其所做的更改。

有关 C# 参数传递的更多详细信息,请参阅 my article on the topic

(顺便说一句,我强烈建议您养成遵循 .NET 命名约定的习惯,即使在演示代码中也是如此。它可以减少阅读它的认知负担。)

更好的选择是使用 ref 而不是 out。您可以这样设置:

public void method1()
{       
        int trycount = 0;     
        ....
        foreach (var gtin in gtins)
        {
            method2(gtin, ref trycount);
        }           

    if (trycount > 5)
    {...}
}

public void method2 (string gtin, ref int trycount)
{
    ......  
    trycount++; // this will modify the variable declared earlier
}