在控制台应用 c# 中使用 out 参数
本文关键字:out 参数 控制台 应用 | 更新日期: 2023-09-27 18:36:43
我正在使用一个使用 C# 的控制台应用程序,该应用程序具有调用另一个方法并传递 out 参数的方法
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,因为在 method1 中第二次执行 foreach 后,trycount 有一个值。我想将变量传回,以便在 foreach 之后我可以检查参数的值。
我知道我可以做一些类似返回 trycount = method2(gtin,trycount)的事情,但如果可能的话,我想尝试使用 out 参数。 谢谢
听起来你想要一个ref
参数而不是一个out
参数。基本上out
就像有一个额外的返回值 - 它最初在逻辑上没有值(它没有明确赋值,必须在方法正常退出之前明确赋值)。
这也是为什么你不必有一个绝对赋值的变量来使用它作为参数:
int x;
// x isn't definitely assigned here
MethodWithOut(out x);
// Now it is
Console.WriteLine(x);
从逻辑上讲,x
在调用 MethodWithOut
时没有任何值,所以如果该方法可以使用该值,您希望它获得什么值?
将此参数与 ref
参数进行比较,该参数在"输入和输出"中有效 - 用于参数的变量必须在调用之前明确分配,参数最初是明确分配的,因此您可以从中读取,并且在方法中对其所做的更改对调用者可见。
有关 C# 参数传递的更多详细信息,请参阅我关于该主题的文章。
(顺便说一句,我强烈建议您养成即使在演示代码中也遵循 .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
}