Make a shortcut for Console.WriteLine()

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

    You could no doubt create a Visual Studio snippet for it (although actually there's one already for cw, apparently - try it!).

    I would personally suggest that you don't use a shortcut within the code - it's likely to be clearer to anyone reading it if it still says Console.WriteLine.

    Depending on what this is for, it may make sense to write a helper method called, say, Log - that has a reasonable meaning, whereas CW doesn't.

    (If this is for logging, consider using something more powerful such as log4net, too.)

    0 讨论(0)
  • 2020-12-23 20:26

    If you have ReSharper you can type out and Enter and the row

    Console.Out.WriteLine("");
    

    will be written.

    In case you want to output a variable there is another live template: outv.

    Console.Out.WriteLine("time = {0}", time);
    

    Here time is a variable which you could select after typing outv.

    0 讨论(0)
  • 2020-12-23 20:26

    Write a method which returns void and call it for Console.WriteLine().

    void Log(string msg)
    {
       Console.WriteLine(msg);
    }
    
    0 讨论(0)
  • 2020-12-23 20:31

    Visual Studio already has a default code snippet for this. Just type cw and press tab. Note that if you're considering using a method, it may lack some features like the automatic string.Format and other overloaded parameters.

    0 讨论(0)
  • 2020-12-23 20:32

    You could declare a static method to wrap the call:

    static class C
    {
        static void W(string s)
        {
            Console.WriteLine(s);
        }
    }
    

    then:

    C.W("Print Something");
    

    I would be inclined to use the "inline method" refactoring before checking in any code that calls this method. As Jon Skeet notes, it's less confusing simply to use Console.WriteLine directly.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题