[英]How to print variables using Console.WriteLine
The following code demonstrates the use of the sleep() method for making a thread pause for a specific period of time. 以下代码演示了使用sleep()方法使线程在特定时间段内暂停。
When I run this code :- 当我运行此代码时:-
class Program
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
// the thread is paused for 5000 milliseconds
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds");
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
I get this output- 我得到这个输出
In Main: Creating the child thread
Child thread starts
Child thread paused for <0> seconds
Child thread resumes
But what i expect is :- 但是我期望的是:-
In Main: Creating the child thread
Child thread starts
Child thread paused for <5> seconds
Child thread resumes
How can I do it any suggestions? 我该怎么做任何建议?
I think this is where you mistake is: 我认为这是您的错误所在:
Console.WriteLine("Child Thread Paused for {0} seconds", (sleepfor/1000).ToString());
You didn't specify where the value for the {0}
comes from. 您未指定
{0}
的值来自何处。
Also you need to calculate from milliseconds to seconds, thats why /1000
另外您还需要计算毫秒到秒,这就是为什么
/1000
If you want to see Child thread passed for <5> seconds
, then you need to print exactly that. 如果要查看
Child thread passed for <5> seconds
,则需要完全打印该Child thread passed for <5> seconds
。
Below is the problem line of your code 下面是您的代码的问题行
Console.WriteLine("Child Thread Paused for {0} seconds");
This should be 这应该是
Console.WriteLine("Child Thread Paused for <{0}> seconds", sleepfor/1000);
As you notice, you haven't specified the parameter {0}
in your call. 如您所见,您尚未在调用中指定参数
{0}
。 You can refer to the documentation on Console.WriteLine()
您可以参考
Console.WriteLine()
上的文档。
Note that Console.WriteLine
follows the formatting rules set by String.Format
. 请注意,
Console.WriteLine
遵循String.Format
设置的格式设置规则。 The format string rules can be seen here . 格式字符串规则可以在这里看到 。
In the newer syntax you don't need to use the place holders like {0}
but can embed the expression itself in the string, called Interpolated Strings 在较新的语法中,您无需使用
{0}
类的占位符,而是可以将表达式本身嵌入在称为插值字符串的字符串中
Console.WriteLine($"Child Thread Paused for <{sleepfor/1000}> seconds");
Console.WriteLine("Child Thread Paused for <{0}> seconds", sleepfor/1000);
或C#6方法:
Console.WriteLine($"Child Thread Paused for <{sleepfor/1000}> seconds");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.