C# 从.NET 4.0方法向控制台打印字符串

C# 从.NET 4.0方法向控制台打印字符串,c#,C#,昨天我问了一个关于方法如何写入控制台的问题。今天,我写了一个快速的小程序,它不像我想象的那样工作。链接中的程序从未从Main方法调用过向控制台写入任何内容,但是文本将出现在那里。我试图用下面的小片段遵循同样的逻辑,但它什么也没做。为什么下面的程序不在控制台上写“hello”这个词呢?编辑: 链接的程序创建一个计时器,该计时器具有一个事件处理程序,可向控制台写入数据。每当计时器“滴答”一声,它就会调用TimerHandler 您在问题中发布的代码没有类似的内容-没有任何内容以任何方式、形状或形式引

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


链接的程序创建一个计时器,该计时器具有一个事件处理程序,可向控制台写入数据。每当计时器“滴答”一声,它就会调用
TimerHandler


您在问题中发布的代码没有类似的内容-没有任何内容以任何方式、形状或形式引用
WriteIt

您从未从
Main
调用
WriteIt
方法

Main
内部,您应该调用该方法:

static void Main(string[] args)
{
    WriteIt("Hello");
}
注意:您的
WriteIt
方法实际上并不需要
string
参数。您没有在任何地方使用传入的值。您应该将传入的字符串写入
控制台
,或者根本没有参数

为什么下面的程序不在控制台上写“hello”这个词呢

您从未在
Main
中调用
WriteIt
方法,因此它从未被使用过

更改代码以调用它,即:

static void Main(string[] args)
{
    WriteIt("World"); // Call this method

在链接问题中,在
Main
中设置的
System.Timers.Timer
实例调用方法
TimerHandler
。在这个程序的
Main
中没有任何东西调用
WriteIt
,因此它永远不会被调用

// 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();
要使其正常工作,只需调用
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
}

因为您不调用方法
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
int[]DaysInMonth={31,28,31,30,31,30,31,31,30,31};
Console.Write(“输入月份编号:”);
int month=Convert.ToInt32(Console.ReadLine());
WriteLine(“该月有{0}天”,DaysInMonth[month-1]);

写(“一些字符串”);我刚刚测试了代码,它实际上会写入控制台。也许您想暂停执行,以便使用
Console.Read()查看它在末尾。从Main调用
WriteIt
。在Main方法中,您没有调用WriteIt方法,因此它永远不会打印“hello”。我认为您非常困惑。你甚至没有调用“WriteIt”方法。我以为罪魁祸首是我甚至连处理程序都不懂。当我调用WriteIt(“并在此处添加文本”)时,引擎盖下会发生什么。我看到只有方法本身中的文本被打印出来。@wootscootinboogie:对不起,从您的评论中不清楚您在问什么,或者您所说的“只有方法本身中的文本被打印出来”是什么意思。如果我键入`WriteIt(“adfkadf”);大体上,我仍然可以看到打印到控制台的方法中的任何字符串,因为您硬编码了传递给WriteIt的console.WriteLine的字符串值。你甚至没有用这个方法的论点做任何事。谢谢。令人困惑的是,我不理解事件处理程序,在Main方法中也没有看到类似
TimerHandler()
的内容。如果我尝试在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