Dan*_*ber 8 c# code-formatting visual-studio
如何在Visual Studio 2017 (C# 7) 中禁用特定代码块的代码格式?
我有这个方法:
public CarViewModel(ICarsRepo carsRepo)
{
...
Manufacturers = ToSelectList<Manufacturer>();
Categories = ToSelectList<Category>();
States = ToSelectList<State>();
}
Run Code Online (Sandbox Code Playgroud)
我想像这样格式化它:
public CarViewModel(ICarsRepo carsRepo)
{
...
Manufacturers = ToSelectList<Manufacturer>();
Categories = ToSelectList<Category>();
States = ToSelectList<State>();
}
Run Code Online (Sandbox Code Playgroud)
但是当我按下Ctrl K+ 时Ctrl D,它又回到原来的样子。
#region
灵感我想要一些东西来包装特定的代码块,例如#region
:
public CarViewModel(ICarsRepo carsRepo)
{
...
#region disable_format
Manufacturers = ToSelectList<Manufacturer>();
Categories = ToSelectList<Category>();
States = ToSelectList<State>();
#endregion
}
Run Code Online (Sandbox Code Playgroud)
#pragma
灵感或者不一定是region
,也许是pragma
在这个代码片段中使用的:
var parameter = 0;
var sqlCommand = $"{parameter}";
#pragma warning disable EF1000 // Possible SQL injection vulnerability.
this.Database.ExecuteSqlCommand(sqlCommand);
#pragma warning restore EF1000 // Possible SQL injection vulnerability.
Run Code Online (Sandbox Code Playgroud)
这更多是一种审美偏好,大多数开发人员可能不会共享这种偏好,但我不时在我的代码中非常喜欢这种偏好。
Visual Studio(参考)
#pragma warning disable format
#pragma warning restore format
switch (number) {
#pragma warning disable format
case 1: cardinal = "one"; animal = "monkey"; break;
case 2: cardinal = "two"; animal = "horse"; break;
case 3: cardinal = "three"; animal = "pig"; break;
case 4: cardinal = "four"; animal = "chicken"; break;
#pragma warning restore format
}
Run Code Online (Sandbox Code Playgroud)
骑士( doc )
// @formatter:off
// @formatter:on
switch (number) {
// @formatter:off
case 1: cardinal = "one"; animal = "monkey"; break;
case 2: cardinal = "two"; animal = "horse"; break;
case 3: cardinal = "three"; animal = "pig"; break;
case 4: cardinal = "four"; animal = "chicken"; break;
// @formatter:on
}
Run Code Online (Sandbox Code Playgroud)
组合
switch (number) {
#pragma warning disable format // @formatter:off
case 1: cardinal = "one"; animal = "monkey"; break;
case 2: cardinal = "two"; animal = "horse"; break;
case 3: cardinal = "three"; animal = "pig"; break;
case 4: cardinal = "four"; animal = "chicken"; break;
#pragma warning restore format // @formatter:on
}
Run Code Online (Sandbox Code Playgroud)