将 Null 附加到 StringBuilder

Append Null to `StringBuilder`

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

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

我不确定这是否是您要找的?

if (key != null)
    sb.Append(key.PadRight(33));
else
    sb.Append("".PadRight(33));

你可以简单地写

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

那个??被称为 Null-Coalescing operator

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

的快捷方式
sb.Append((key == null ? "" : key).PadRight(33));

你可以这样做: sb.Append(key?.PadRight(33));