Ben*_*enk 1 c# console-application
我正在使用一个使用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++;
}
Run Code Online (Sandbox Code Playgroud)
我不想覆盖trycount变量= 0,因为在第二次foreach在method1中执行后,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);
Run Code Online (Sandbox Code Playgroud)
从逻辑上讲,x
当你调用时没有任何值MethodWithOut
,所以如果方法可以使用该值,你期望得到什么值?
将此与一个ref
有效"进出" 的参数进行比较- 在调用之前必须明确分配用于参数的变量,该参数最初是明确赋值的,因此您可以从中读取,并对其进行更改调用者可以看到该方法中的内容.
有关C#参数传递的更多详细信息,请参阅有关该主题的文章.
(顺便说一句,我强烈建议您养成遵循.NET命名约定的习惯,即使在演示代码中也是如此.它减少了阅读它的认知负担.)