如何去掉单行语句上的大括号?

问题描述 投票:0回答:3

有人可以建议如何从任何单行语句中删除大括号吗? (排除明显的只需手动删除大括号)

在 Visual Studio 中使用 C#。

所以代替:

if (thingy is null)
{
    throw new ArgumentNullException(nameof(thingy));
}

有替代方案:

if (thingy is null)
    throw new ArgumentNullException(nameof(thingy));

我尝试运行 CodeMaid 并更改 CodeCleanup (这只是将其更改回带有大括号)。 我很高兴尝试任何推荐的扩展等来解决这个问题。

c# visual-studio curly-braces code-cleanup codemaid
3个回答
5
投票

如果您使用的是 Visual Studio 2019 Preview,那么只需 2 个简单步骤即可实现您的需求。


3
投票

这不是 Visual Studio 中的标准重构。但有一些扩展可以添加此功能。

例如。 Roslynator 有其Remove Braces 重构。


-5
投票

您不应该养成在单行条件上省略大括号的习惯。某人(您或其他人)很容易犯一个小错误,从而产生一个您必须稍后处理的错误。

现在我将离开我的肥皂盒并分享一个更短的空保护:

public void MyFunction(object thingy)
{
   _ = thingy ?? throw new ArgumentNullException(nameof(thingy));
   etc...

简洁明了,并且没有丢失支架问题的风险。对于字符串,我将使用一种扩展方法来获得相同的衬里。

  public static string NullIfWhiteSpace(this string s)
  {
      return string.IsNullOrWhiteSpace(s) ? null : s;
  }

那么我可以做:

public void MyFunction(string stringy)
{
   _ = stringy.NullIfWhiteSpace() ?? throw new ArgumentNullException(nameof(stringy));
   etc...

我对空列表和字典做了类似的事情。

© www.soinside.com 2019 - 2024. All rights reserved.