【问题标题】:c# long line of code formattingc#长行代码格式化
【发布时间】:2017-04-15 23:29:16
【问题描述】:

我写了这行代码。这是不可读的。有没有巧妙的方法将其分解为多行

Console.WriteLine(String.Join("\n", testResults.Select(row => String.Join("|", row.Select(column => String.Format("{0,20}", column.ToString()))))));

【问题讨论】:

  • 你能定义聪明吗?
  • 一个提示:应该使用 column.ToString("...") 而不是最后一个 String.Format。
  • 我想说这不是格式化而是嵌套。然后,我会将其拆分为多个表达式,一行一行地使用多个临时变量来存储稍后使用的值。
  • @TimBarrass 让它“可读”和“看起来不错”

标签: c# code-formatting


【解决方案1】:

我建议将 query 本身和它的最终 representation(控制台输出)分开:

// Query: what to output
var testReport = testResults
  .Select(row => String.Join("|", row
     .Select(column => String.Format("{0,20}", column)))); // .ToString() is redundant

// Representation: how to output (print on the console in one go)
Console.WriteLine(String.Join(Environment.NewLine, testReport));

【讨论】:

    【解决方案2】:

    如果您不想拆分作业,这应该是最短的方法。但我会建议拆分它,所以最好阅读。

    Console.WriteLine(String.Join("\n",
                    testResults.Select(
                        row => String.Join("|", row.Select(column => String.Format("{0,20}", column.ToString()))))));
    

    【讨论】:

      【解决方案3】:

      是的..提取行。选择到上面一行的变量中并使用它。同样提取 testResults.Select 。

      【讨论】:

      • 为什么投反对票?这个答案和其他答案几乎完全一样,只是没有代码。
      猜你喜欢
      • 2019-04-14
      • 2011-07-19
      • 2021-09-21
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 2014-07-02
      • 2018-05-01
      相关资源
      最近更新 更多