在具有返回值的函数中使用out参数

t_p*_*lus 2 c#

我有一个像这样的功能:

public string MyFunction(int a, out int b)
{
   var test = ""
   b = 6;
   return test;
}
Run Code Online (Sandbox Code Playgroud)

然后在接收端:

int b = 0;
var testOutcome = MyFunction(3, b);
Run Code Online (Sandbox Code Playgroud)

我想知道如何在这种情况下获得:b的值?

就像是:

var bOutcome = ....; 
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 7

您out从方法中获取参数.请注意,您还需要out在方法的参数签名中添加关键字:

int b = 0;  // initialization is redundant
string  testOutcome = MyFunction(3, out b);
// b is initialized now
Run Code Online (Sandbox Code Playgroud)

尽管作为out参数传递的变量在传递之前不必初始化,但是在方法返回之前需要调用方法来赋值.