在使用方法时,我需要将一个字符串从方法返回到main中。 该字符串需要包含程序的输出。主要需要显示字符串的那个。
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函数显示输出。
答案 0 :(得分:1)
是的,有这种方法。
def profile_view(request, profile_type: str, pk: int):
user = request.user
if profile_type == 'partner':
"""
do something
"""
template_name = 'partner_handler.html'
context = dict()
elif profile_type == 'student':
"""
do something
"""
template_name = 'student_handler.html'
context = dict()
return render(request, template_name, context)
使用这种方式,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
中获取值。
但是,按照另一个答案中的建议重写方法会更正确。
答案 1 :(得分: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));
}