【问题标题】:Is AppendFormat() or AppendLine() the safer/sleeker solution?AppendFormat() 或 AppendLine() 是更安全/更时尚的解决方案吗?
【发布时间】:2014-07-28 02:01:27
【问题描述】:

我一直在创建动态字符串以附加到 StringBuilder,如下所示:

StringBuilder sb = new StringBuilder();
string bla = "bla";
sb.AppendLine(string.Format("android:id=\"@+id/{0}\" ", bla));

...但后来我注意到 StringBuilder 有一个 AppendFormat() 方法,它消除了“string.Format()”。所以我想知道 AppendFormat() 是否也像 AppendLine() 那样添加换行符(而不是 Append(),后者没有)。

IOW,达到同样的效果:

sb.AppendLine(string.Format("android:id=\"@+id/{0}\" ", bla));

...当使用 AppendFormat() 时,我需要使用两行,如下所示:

sb.AppendFormat("android:id=\"@+id/{0}\" ", bla);
sb.AppendLine();

?

答案是肯定的 - 需要两行,或者我必须在 AppendLine() 调用中恢复为显式使用 string.Format()。

实际上,至少有一种方法可以在一行中使用 AppendFormat() 来完成,也就是说:

sb.AppendFormat("android:id=\"@+id/{0}\" {1}", bla, Environment.NewLine);

...但这可以说不比 AppendLine(string.Format(...

那么以下哪一项更好(性能更高)或更安全,或者无关紧要?

sb.AppendFormat("android:id=\"@+id/{0}\" {1}", bla, Environment.NewLine);
sb.AppendLine(string.Format("android:id=\"@+id/{0}\" ", bla));

【问题讨论】:

    标签: c# performance append stringbuilder string.format


    【解决方案1】:

    最具可读性的是:

    sb.AppendFormat("android:id=\"@+id/{0}\" ", bla)
      .AppendLine();
    

    string.Format 在内部使用StringBuilder,所以我不会使用sb.AppendLine(string.Format())

    【讨论】:

      【解决方案2】:

      只需创建您自己的同时调用AppendLineAppendFormat 的扩展方法,即可创建您想要的方法,能够使用格式字符串追加一行而无需显式添加新行字符:

      public static StringBuilder AppendLineFormat(
          this StringBuilder builder,
          string formatString,
          params object[] args)
      {
          return builder.AppendFormat(formatString, args)
              .AppendLine();
      }
      

      (如果您愿意,可以为 AppendFormat 的每个重载创建一个重载。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-26
        • 1970-01-01
        • 2011-11-21
        • 2013-11-19
        • 2021-05-06
        • 1970-01-01
        • 1970-01-01
        • 2010-09-29
        相关资源
        最近更新 更多