在使用方法时,我需要将一个方法的字符串返回到主方法中。该字符串需要包含程序的输出。主要需要显示字符串的那个。
public static string GetFlightInfo(int flight, int[] flightNumbers, string[] codes, string[] names, string[] times)
{
int y = 0;
string random = "";
for (int x =0; x<flightNumbers.Length; ++x)
{
if (flight == flightNumbers[x])
{
Write("Flight #{0} {1} {2} Scheduled at: {3}", flight, codes[x], names[x], times[x]);
y++;
break;
}
}
if (y == 0)
{
WriteLine("Flight #{0} was not found", flight);
}
return random;
}
我想将WriteLine存储到随机字符串中。并使Main函数显示输出。
是的,有这种方法。
var previous = Console.Out; // backup current state
var writer = new StringWriter();
Console.SetOut(writer);
GetFlightInfo(...);
Console.SetOut(previous); // restore the original state
string result = writer.ToString();
Console.WriteLine(result);
使用这种方式,WriteLine
方法将写入StreamWriter
而不是控制台。然后,您可以从此StreamWriter
中获取值。
但是,按照另一个答案中的建议重写方法会更正确。
难道你不能这样做吗?
public static string GetFlightInfo(int flight, int[] flightNumbers, string[] codes, string[] names, string[] times)
{
int y = 0;
string random = "";
for (int x =0; x<flightNumbers.Length; ++x)
{
if (flight == flightNumbers[x])
{
random += $"Flight #{flight} {codes[x]} {2} Scheduled at: {times[x]}\n";
y++;
break;
}
}
if (y == 0)
{
random += $"Flight #{flight} was not found";
}
return random;
}
main() {
Console.WriteLine(GetFlightInfo(flight, flightNumbers, codes, names, times));
}