我正在使用一个使用out参数的函数的API .我想out在while循环中使用其中一个参数中的值.例如:
static int counter = 0;
static void getCounterValue(out int val)
{
val = counter;
counter++;
}
static void Main()
{
// Right now, I'm having to do this:
int checkVal = 0; // I have to figure out an appropriate starting value.
while (checkVal < 10)
{
getCounterValue(out checkVal);
Console.WriteLine("Still waiting.");
}
Console.WriteLine("Done.");
}
Run Code Online (Sandbox Code Playgroud)
有没有更简单的语法来做到这一点?我想要更经典的东西while (getCounterValue() < 10),但我必须处理out参数,因为它是一个我无法改变的API.
你不能直接做任何事情,方法调用的返回值是while将要使用的,而不是你想要的值.如果这导致您出现问题,您可以始终包装方法调用:
int wrappedGetCounterValue()
{
int i;
getCounterValue(out i);
return i;
}
Run Code Online (Sandbox Code Playgroud)
或者使用C#7:
int wrappedGetCounterValue()
{
getCounterValue(out int i);
return i;
}
Run Code Online (Sandbox Code Playgroud)
并在while循环中使用它.
while (wrappedGetCounterValue() < 10)
....
Run Code Online (Sandbox Code Playgroud)