StringBuilder,如果满足条件,则追加字符串

时间:2014-12-19 14:25:24

标签: c# .net stringbuilder

var sb = new StringBuilder ();

if (condition1) sb.Append ("one");
if (condition2) sb.Append ("two");
if (condition3) sb.Append ("three");
if (condition4) sb.Append ("four");
if (condition5) sb.Append ("five");

return sb.ToString ();

知道如何改进吗?如何编写更少的代码,给出相同的结果?

4 个答案:

答案 0 :(得分:9)

这段代码很好。保持这样。

  • 每次尝试使用扩展方法或其他方法只会使此代码不易理解和维护;
  • 没有重复的代码;
  • 只要条件不影响他人,就无法缩短if s。

如果您确实需要其他选项:

string s = 
   (condition1 ? "one" : null) + 
   (condition2 ? "two" : null) + 
   (condition3 ? "three" : null) + 
   (condition4 ? "four" : null) + 
   (condition5 ? "five" : null)
   ;

但是说实话,这会让它变得更好吗?否。

答案 1 :(得分:2)

你可以做点什么,

var conditions = new[]
    {
        Tuple.Create(condition1, "one"),
        Tuple.Create(condition2, "two"),
        Tuple.Create(condition3, "three"),
        Tuple.Create(condition4, "four"),
        Tuple.Create(condition5, "five"),
    }

return string.Concat(conditions.Where(t => t.Item1).Select(t => t.Item2));

这样更好吗?否。

答案 2 :(得分:2)

当使代码更简单或更易读时,我更喜欢使用简单的DSL定义。 “管道式”表达也很棒。 在你的情况下,它可以这样写:

var str =
    new StringBuilder()
        .AppendIf(condition1, "one")
        .AppendIf(condition2, "two")
        .AppendIf(condition3, "forty two")
        .ToString();

使用扩展方法。

public static class StringBuilderExtensions
{
    public static StringBuilder AppendIf(
        this StringBuilder @this,
        bool condition,
        string str)
    {
        if (@this == null)
        {
            throw new ArgumentNullException("this");
        }

        if (condition)
        {
            @this.Append(str);
        }

        return @this;
    }
}
如果条件重复,

方法适用于此处。例如arg1 != nullarg2 != null,则可以使用AppendIfNotNull

否则,请三思而后行,因为它看起来与初始实现非常相似,需要额外的代码,因为额外的空检查和方法调用可能会更慢,并且您还应该为每个{{1创建AppendIf重载一个。

答案 3 :(得分:0)

另一种方法是使用字符串插值,如此处记录https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated。因此,可以像这样修改示例。我觉得它更容易阅读。

var s = $"{(condition1 ? "one": null)}{(condition2 ? "two": null)}{(condition3 ? "three": null)}{(condition4 ? "four": null)}{(condition5 ? "five": null)}";

编辑: 您可以通过逐字字符串文字使代码更容易阅读。

var s = $@"{
    (condition1 ? "one": null)
}{
    (condition2 ? "two": null)
}{
    (condition3 ? "three": null)
}{
    (condition4 ? "four": null)
}{
    (condition5 ? "five": null)}";
相关问题