Console.Writeline basics

前端 未结 3 2054
余生分开走
余生分开走 2021-01-03 23:45

I have a question about the following code:

class CurrentDate
    {
        static void Main()
        {
            Console.WriteLine(DateTime.Now);
                


        
3条回答
  •  余生分开走
    2021-01-04 00:40

    Contrary to what some persons think, DateTime.ToString() won't be called. In .NET, an object can have two ways to "stringize" itself: overriding the string Object.ToString() method and implementing the IFormattable interface. DateTime does both.

    Now... When you try doing

    Console.WriteLine(DateTime.Now);
    

    the void public static void WriteLine(Object value) overload is selected (you can see it if you Ctrl+Click on WriteLine in Visual Studio). This method simply calls the TextWriter.WriteLine(value) method, that does:

    IFormattable f = value as IFormattable;
    if (f != null)
        WriteLine(f.ToString(null, FormatProvider));
    else
        WriteLine(value.ToString());
    

    All of this can be easily seen using ILSpy and looking for the Console.WriteLine.

提交回复
热议问题