When do you use StringBuilder.AppendLine/string.Format vs. StringBuilder.AppendFormat?

前端 未结 7 724
半阙折子戏
半阙折子戏 2021-01-31 13:34

A recent question came up about using String.Format(). Part of my answer included a suggestion to use StringBuilder.AppendLine(string.Format(...)). Jon Skeet suggested this was

7条回答
  •  佛祖请我去吃肉
    2021-01-31 14:15

    Just create an extension method.

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

    Reasons I prefer this:

    • Doesn't suffer as much overhead as AppendLine(string.Format(...)), as stated above.
    • Prevents me from forgetting to add the .AppendLine() part at the end (happens frequently enough).
    • Is more readable (but that is more of an opinion).

    If you don't like it being called 'AppendLine,' you could change it to 'AppendFormattedLine' or whatever you want. I enjoy everything lining up with other calls to 'AppendLine' though:

    var builder = new StringBuilder();
    
    builder
        .AppendLine("This is a test.")
        .AppendLine("This is a {0}.", "test");
    

    Just add one of these for each overload you use of the AppendFormat method on StringBuilder.

提交回复
热议问题