【发布时间】:2020-11-05 04:28:32
【问题描述】:
string o=null;
Console.WriteLine($"Hello World '{o}'");
这个输出:
你好世界''
我想为空值明确写“null”。
string o=null;
Console.WriteLine($"Hello World '{o??"null"}'");
这就是这样做的:
Hello World 'null'
但如果o 不是string(或Object)类型,则会产生编译错误。例如:
Array o=null;
Console.WriteLine($"Hello World '{o??"null"}'");
编译错误运算符'??'不能应用于“数组”和“字符串”类型的操作数
实现预期结果的最佳方法是什么?很遗憾,您无法修改 $ 处理 null 的方式,因为它似乎硬编码为使用 String.EmptyString
【问题讨论】:
-
$"{o?.ToString() ?? "null"}"? -
@juharr 呸!这似乎抵消了
$的全部好处。可以以某种方式将其拉出到实用程序方法中吗?很遗憾,您无法修改$处理null的方式,因为它似乎硬编码为使用String.EmptyString -
@Mr.Boy 好吧,输出“null”不是常见的要求。这通常不是您希望最终用户看到的词。
-
即使你这样做了,你也可以随时覆盖 ToString
-
@Mr.Boy 你总是可以把它变成一个扩展方法并调用它,即
public static string ToStringWithNullOutput(this object input) => input is null ? "null" : input.ToString();然后你的调用代码在语义上是清晰的,没有人会得到意外的行为。Console.WriteLine($"Hello World '{oToStringWithNullOutput()");
标签: c# null conditional-operator string-interpolation null-coalescing-operator