Make a shortcut for Console.WriteLine()

前端 未结 14 1463
北恋
北恋 2020-12-23 19:55

I have to type Console.WriteLine() many times in my code. Is it possible to create a shortcut for Console.WriteLine so that I can use it like...

CW=Console.Wr         


        
14条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 20:35

    // For formatting string and parameters define a function
    // The shortcut function wl, kind of write line
    public void wl( string format, params object[] parms){
        Console.WriteLine(format, parms);
    }
    
    // Just for strings we can use Action delegate
    Action ws = Console.WriteLine;
    
    // examples:
    ws("String with no formatting parameters");
    
    wl("String without formatting parameters");
    wl("String with {0} parameters {1}", 2, "included");
    wl("several parameters {0} {1} {2} repeated {0}", 1234, 5678, 6543);
    

    or using extension method: formatString.wl(arguments...)

    public static class ConsoleWriteExtensions
    {
        public static void wl(this string format, params object[] parms){
            Console.WriteLine(format, parms);
        }
    }
    
    "{0} -> {1}".wl("Mili",123.45); // prints Mili -> 123.45
    

提交回复
热议问题