是否可以将WriteLine存储到字符串变量中?

问题描述 投票:-1回答:2

在使用方法时,我需要将一个方法的字符串返回到主方法中。该字符串需要包含程序的输出。主要需要显示字符串的那个。

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函数显示输出。

c#
2个回答
1
投票

是的,有这种方法。

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中获取值。

但是,按照另一个答案中的建议重写方法会更正确。


0
投票

难道你不能这样做吗?

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));
}

$ - string interpolation (C# reference)

© www.soinside.com 2019 - 2024. All rights reserved.