Make a shortcut for Console.WriteLine()

前端 未结 14 1436
北恋
北恋 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:32

    This shortcut will avoid exceptions being thrown when you use a composite formatting overload like Console.WriteLine(String, Object[]) and the number of format items in format and the number of items in the argument list, args, differ:

    public bool WriteToConsole(string format, params object[] args)
    {           
        var succeeded = false;
        var argRegex = new Regex(@"\{\d+\}");
        if ((args != null) && (argRegex.Matches(format).Count == args.Length))
        {
            Console.WriteLine(format, args);
            succeeded = true;
        }
        else
        {
            Console.WriteLine(format);
        }
        return succeeded;
    }
    

提交回复
热议问题