繁体   English   中英

如何使用Console.WriteLine打印变量

[英]How to print variables using Console.WriteLine

以下代码演示了使用sleep()方法使线程在特定时间段内暂停。

当我运行此代码时:-

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();
        }
    }
}

我得到这个输出

In Main: Creating the child thread
Child thread starts
Child thread paused for <0> seconds
Child thread resumes

但是我期望的是:-

In Main: Creating the child thread
Child thread starts
Child thread paused for <5> seconds
Child thread resumes

我该怎么做任何建议?

我认为这是您的错误所在:

Console.WriteLine("Child Thread Paused for {0} seconds", (sleepfor/1000).ToString());

您未指定{0}的值来自何处。

另外您还需要计算毫秒到秒,这就是为什么/1000

如果要查看Child thread passed for <5> seconds ,则需要完全打印该Child thread passed for <5> seconds

下面是您的代码的问题行

Console.WriteLine("Child Thread Paused for {0} seconds");

这应该是

Console.WriteLine("Child Thread Paused for <{0}> seconds", sleepfor/1000);

如您所见,您尚未在调用中指定参数{0} 您可以参考Console.WriteLine()上的文档。

请注意, Console.WriteLine遵循String.Format设置的格式设置规则。 格式字符串规则可以在这里看到

在较新的语法中,您无需使用{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.

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