简体   繁体   English

c#将console.writeline转换为字符串

[英]c# convert console.writeline to a string

I want a code that takes the text that was written on the console and put it on a string variable, plz. 我想要一个代码,它接受在控制台上写的文本并将其放在字符串变量plz上。 Something like this: 像这样的东西:

string s = Console.WriteLine(Invoke(o, null));

I want it with console because if I invoke it without it I can't get the text from it. 我想用控制台,因为如果我在没有它的情况下调用它,我就无法从中获取文本。

I hope you understand it. 我希望你理解它。

I got what I want 我得到了我想要的东西

using (StringWriter stringWriter = new StringWriter())
        {
            Console.SetOut(stringWriter);
            Console.Write(mi.Invoke(o, null));
            string allConsoleOutput = stringWriter.ToString();

            MessageBox.Show(allConsoleOutput, "Output");
        }

thank for every one! 谢谢每一个人!

You can't do this directly. 你不能直接这样做。 I think you can somehow do it by getting the console window object or something like that, but it's really not worth the time to do that when you just want the output of Console.WriteLine . 我认为你可以通过获取控制台窗口对象或类似的方式来实现它,但是当你只想要Console.WriteLine的输出时,真的不值得花时间去做。

There are a lot of overloads of Console.WriteLine , but in the end all the overloads will convert the parameter to a string, using ToString . Console.WriteLine有很多重载,但最后所有重载都会使用ToString将参数转换为字符串。 So, to put the output of Console.WriteLine in a string variable, just call ToString on the argument. 因此,要将Console.WriteLine的输出放在字符串变量中,只需在参数上调用ToString

string s = Invoke(o, null).ToString();

What if you want to both print, and store the output? 如果要同时打印存储输出怎么办? You can do it like this: 你可以这样做:

string s = Invoke(o, null).ToString();
Console.WriteLine(s);

See the documentation of Console.WriteLine() , which will Writes the specified data, followed by the current line terminator, to the standard output stream. 请参阅Console.WriteLine()的文档,该文档将指定的数据(后跟当前行终止符Console.WriteLine()写入标准输出流。 doesn't return anything to assign to a variable, it's return type is void 不返回任何赋值给变量,它的返回类型为void

If You Want Print Text : 如果您想要打印文本:

Console.WriteLine("Enter a name");

If You Want Enter Any Text : 如果您想输入任何文字:

 string name = Console.ReadLine();

Try This Way. 试试这个方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM