gpt4 book ai didi

c# - 将 Null 附加到 `StringBuilder`

转载 作者:数据小太阳 更新时间:2023-10-29 02:16:06 24 4
gpt4 key购买 nike

我正在读取 XML 文件并使用 StringBuilder 构建字符串。但有时我的 Element.Attributes 会丢失,在这种情况下字符串为空。

string key  = (string)EventId.Descendants("properties").Elements("ID").Attributes("key").FirstorDefault();

获取所有属性值后,我正在构建一个字符串:

sb.Append(key.PadRight(33));

但是有时候key的值可以为null,报错:

Check to determine if the object is null before calling the method

我想将空字符串附加到 StringBuilder,即使值为 null。

最佳答案

你可以简单地写

 sb.Append((key ?? "").PadRight(33));

那个??称为 Null-Coalescing operator

它的工作在于评估左侧值,如果该值为空,则返回右侧值。或者换句话说,它是

sb.Append((key == null ? "" : key).PadRight(33));

关于c# - 将 Null 附加到 `StringBuilder`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44733617/

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