-1

昨天我在这里问了一个关于方法如何写入控制台的问题。今天,我编写了这个快速的小程序,但它并没有像我想象的那样工作。链接中的程序从未调用 Main 方法向控制台写入任何内容,但文本仍会出现在那里。我尝试使用下面的小片段遵循相同的逻辑,但它没有做任何事情。为什么下面的程序没有向控制台写入单词“hello”?编辑:链接在这里

using System;
class DaysInMonth
{
    static void Main(string[] args)
    {
        int[] DaysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        Console.Write("enter the number of the month: ");
        int month = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("that month has {0} days", DaysInMonth[month - 1]);

    }
    static void WriteIt(string s)
    {
        string str = "hello";
        Console.WriteLine(str);
    }
}
4

5 回答 5

6

The linked program creates a timer which has an event handler which writes to the console. Every time the timer "ticks", it will call TimerHandler.

The code you've posted in the question doesn't have anything like that - nothing refers to WriteIt in any way, shape or form.

于 2012-09-25T16:52:12.947 回答
2

Why isn't the program below writing the word "hello" to the console?

You never call the WriteIt method in your Main, so it's never used.

Change your code to call it, ie:

static void Main(string[] args)
{
    WriteIt("World"); // Call this method
于 2012-09-25T16:52:19.010 回答
2

In the linked question the method TimerHandler is invoked by the System.Timers.Timer instance set up in Main. Nothing invokes WriteIt in this program's Main and so it is never invoked.

// In the linked question's Main method
// Every time one second goes by the TimerHandler will be called
// by the Timer instance.
Timer tmr = new Timer();
tmr.Elapsed += new ElapsedEventHandler(TimerHandler);
tmr.Interval = 1000;
tmr.Start();

To make it work you simply need to call WriteIt:

static void Main(string[] args)
{
    int[] DaysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    Console.Write("enter the number of the month: ");
    int month = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("that month has {0} days", DaysInMonth[month - 1]);
    WriteIt("Greetings!"); // Now it runs
}
于 2012-09-25T16:53:15.663 回答
1

You're never calling your WriteIt method from Main

Inside Main you should be calling the method:

static void Main(string[] args)
{
    WriteIt("Hello");
}

As a note: Your WriteIt method doesn't really need the string parameter. You're not using the value passed in anywhere. You should either write the passed in string to the Console, or not have the parameter at all.

于 2012-09-25T16:52:13.770 回答
1

因为你不调用方法WriteIt

int[] DaysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 
Console.Write("enter the number of the month: "); 
int month = Convert.ToInt32(Console.ReadLine()); 
Console.WriteLine("that month has {0} days", DaysInMonth[month - 1]); 
WriteIt("some string"); <====== //add this
于 2012-09-25T16:53:21.323 回答