gpt4 book ai didi

c# - StringBuilder,如果满足条件追加字符串

转载 作者:太空狗 更新时间:2023-10-30 00:04:50 25 4
gpt4 key购买 nike

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 ();

知道如何改进吗?如何写更少的代码,得到同样的结果?

最佳答案

这段代码没问题。保持这样。

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

如果您确实想要其他选择:

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

但老实说,这会让它变得更好吗?没有。

关于c# - StringBuilder,如果满足条件追加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27567999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com