Console.Writeline basics

前端 未结 3 2043
余生分开走
余生分开走 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:45

    Since there is no overload for Console.WriteLine(DateTime),as in your case,the Console.WriteLine(Object) overload is called and this overload calls the TextWriter.WriteLine(object) overload which is implemented as:

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

    As you can see, this method checks if this object type implements IFormattable interface or not. Since Datetime implements this interface, your f.ToString(null, FormatProvider) will be called. From this method's documentation the first parameter is:

    A null reference (Nothing in Visual Basic) to use the default format defined for the type of the IFormattable implementation.

    And from the DateTime.ToString(String, IFormatProvider) method's documentation:

    If format is null or an empty string (""), the standard format specifier, "G"., is used.

    That means, the representation will be a combination of the ShortDatePattern and LongTimePattern properties belonging to your CurrentCulture

    If you want a special format for your custom class, you can override the .ToString() method of your type to change its behaviour.

提交回复
热议问题