我正在读取 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/