读取已经打印到控制台的值 [英] Read values already printed to the console
问题描述
这可能是完全不可能的,但是我想知道是否有一种方法可以读取控制台已经打印的值。例如,如果控制台打印
This may be completely impossible, but I was wondering if there is a way to read values that the console has already printed. For example, if the console printed
您正以10m / s的速度向北行驶
You are travelling north at a speed of 10m/s
; ,
as a result of Console.WriteLine("You are travelling north at a speed of 10m/s");
, is there a way of reading this line and then, for arguments sake, putting this value in a string?
基本上,我需要阅读已输出到的内容,有没有办法读取此行,然后出于参数目的将其放在字符串中?控制台,而不是用户输入。有办法吗?
Basically what I need is to read what has already been outputted to the console, not the user input. Is there a way?
预先感谢。
推荐答案
是。有一种方法。您可以 Console.SetOut
方法。
Yes. There is a way. You can Console.SetOut
method.
将您的主要方法组织为;
Organize your main method as;
static void Main()
{
using (StringWriter stringWriter = new StringWriter())
{
Console.SetOut(stringWriter);
//All console outputs goes here
Console.WriteLine("You are travelling north at a speed of 10m/s");
string consoleOutput = stringWriter.ToString();
}
}
然后 consoleOutput
应该为您以10m / s的速度向北行驶。
Then consoleOutput
should have You are travelling north at a speed of 10m/s
.
这篇关于读取已经打印到控制台的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!