gpt4 book ai didi

c# - 格式化字符串但省略参数(如果它为空)

转载 作者:行者123 更新时间:2023-11-30 20:20:29 26 4
gpt4 key购买 nike

我在生产代码中有一个情况,请看下面的代码片段来形象化。

string formatStr = "{2} (FC {3:D3}): {1} {0}";
object obj= null;
string str = string.Format(formatStr, "", "10 - 15","Blabla", obj);

此输出将是“Blabla (FC): 10 - 15”

观察到没有与 FC 关联的值,因为 obj 为 null,我不想打印其中没有任何内容的 FC。

所以我到现在为止想的是检查 obj 并从中删除 (FC {3:D3}): 如果 obj 为空,是否有任何其他技术我不必这样做。

最佳答案

您可以在单独的步骤中构建 {3} 的值。

string formatStr = "{2}{3}: {1} {0}";
object obj= null;

string fcValue = (obj == null ? "" : string.Format(" (FC {0:D3})", obj));

string str = string.Format(formatStr, "", "10 - 15", "Blabla", fcValue);

关于c# - 格式化字符串但省略参数(如果它为空),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36606486/

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