我已经学习C#已有3周了,所以仍然涵盖了基础知识.
我的问题:
在程序结束时(例如,一个简单的货币转换器),当用户选择退出该程序(而不是执行其他计算)时,是否可以定时将Console.Writeline设置为在休息前保持可见?
码:
Console.WriteLine("Would you like to perform another conversion?");
Console.WriteLine("");
Console.WriteLine("y for YES");
Console.WriteLine("e for EXIT");
decision = Console.ReadLine();
if (decision.Equals("E", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Thank-you for using CurrencyConverter");
break;
...
//在程序终止之前,上面的写入行是否可以绕几秒钟以提高可读性?
是的,绝对:您可以使用System.Threading.Thread.Sleep(3000)
,其中参数是延迟(以毫秒为单位).
我建议您简单地使用Thread.Sleep(milliseconds)
添加System.Threading
到用法中的可用方法.从字面上看,它正在使当前正在处理程序的线程进入睡眠状态.
PS:除非给定的代码处于循环中,否则break不应在if语句中,因为break通常用于在特定点脱离循环.如果您要退出程序,建议您使用return;
,如果您使用的是main方法或使用Environment.Exit(0);
您可以使用System.Threading.Sleep(int)函数来指定要睡眠的毫秒数.
还有一些其他方法可以使程序等待.例如,您可以让程序等到完成输出读取为止.
一种方法是等待控制台输入:
Console.ReadKey();
或者,如果您使用"开始而不调试"而不是"开始调试",则程序将自动中断并等待按键,然后关闭命令提示符窗口.
I've been learning C# for 3 weeks now so still covering the basics.
My question:
At the end of a program (a simple currency converter, for example), when the user chooses to exit the program (rather than perform another calculation) is it possible to time a Console.Writeline to remain visible before a break?
Code:
Console.WriteLine("Would you like to perform another conversion?");
Console.WriteLine("");
Console.WriteLine("y for YES");
Console.WriteLine("e for EXIT");
decision = Console.ReadLine();
if (decision.Equals("E", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Thank-you for using CurrencyConverter");
break;
...
//is it possible to have the writeline above hang around for a couple of seconds for readability before the program terminates?
Yes, absolutely: you can use System.Threading.Thread.Sleep(3000)
, where the argument is the delay in miliseconds.
I suggest you simply use Thread.Sleep(milliseconds)
which is available once you add System.Threading
to your usings. It is literally putting the thread which is currently taking care of your program into sleep.
PS: Break should not be in your if statement unless the code you have given is in a loop, because break is normally used to break out of loops at a certain point. If you are trying to exit from the program I suggest you rather use return;
, if you are in the main method or by using Environment.Exit(0);
You can use the System.Threading.Sleep(int) function to specify the number of milliseconds to sleep for.
There are also some alternatives to causing the program to wait. For example, you can make the program wait until you are done reading the output.
One way to do that is to wait for console input with:
Console.ReadKey();
Or, if you use "Start Without Debugging" instead of "Start Debugging", then the program will break automatically and wait for a key press before closing the command prompt window.
本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文