如何为Console.WriteLine创建快捷方式

Kis*_*mar 33 .net c#

我必须在我的代码中多次键入Console.WriteLine()所以任何人都可以告诉我为Console.WriteLine创建一个快捷方式,就像我可以使用它一样

CW=Console.WriteLine();
//After that i can use this CW for my Console.WriteLine() like
CW("Print Something");
Run Code Online (Sandbox Code Playgroud)

Chi*_*ata 108

Visual Studio已经有一个默认的代码片段.只需输入cw,然后按Tab键.请注意,如果您正在考虑使用某种方法,则可能缺少某些功能,例如自动string.Format和其他重载参数.

  • 在我的 Visual Studio 副本中 cw<tab><tab> 对我有用。也就是说,我需要在快捷方式后按两次 Tab。 (3认同)

Mic*_*tum 31

如果您使用的是.net 3.5或更高版本:

Action<string> cw = Console.WriteLine;

cw("Print Something");
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 13

毫无疑问,你可以为它创建一个Visual Studio片段(虽然实际上有一个已经用于cw,显然 - 尝试它!).

我个人建议你不要在代码中使用快捷方式- 如果它仍然说,那么阅读它的人可能会更清楚Console.WriteLine.

根据它的用途,编写一个名为的辅助方法可能是有意义的Log- 它具有合理的含义,而CW不是.

(如果这用于日志记录,请考虑使用更强大的功能,例如log4net.)


Jac*_*all 9

C#6增加了这个using static功能:

using static System.Console;

class Program {
  void Main(string[] args) {
     WriteLine("Hello, {0}!", "world");
  }
}
Run Code Online (Sandbox Code Playgroud)

Visual Studio 2015中的IntelliSense了解这种新语法.


Seb*_*ter 5

如果你希望它是全局的,你可以编写一个扩展方法:

public static class StringExtensions
{
   public static void ConLog(this string msg)
   {
     Console.WriteLine(msg);
   }
}
Run Code Online (Sandbox Code Playgroud)

现在,无论您身在何处,都可以调用"My Message".ConLog();应用程序中的任何字符串并将其写入控制台。