我知道做这样的事情是没有意义的:
xstring.ToLower()??"xx"
因为我调用了 ToLower()
在检查 null 之前被调用。
有没有办法解决这个问题,同时保持语法简洁明了?
我可以覆盖字符串的 ??
运算符,以便它仅在 xstring
不是 null 时调用
?ToLower()
最佳答案
您要找的是 Monadic Null Checking .它目前在 C# 5 中不可用,但显然它将在 C# 6.0 中可用。
来自 this post :
7. Monadic 空检查
无需在访问属性或方法之前检查空值。在 Groovy 中称为安全导航运算符。
之前
if (points != null) {
var next = points.FirstOrDefault();
if (next != null && next.X != null) return next.X;
}
return -1;
之后
var bestValue = points?.FirstOrDefault()?.X ?? -1;
与此同时,只需使用
(xstring ?? "xx").ToLower();
正如其他答案所建议的那样。
关于c# - 空合并运算符覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21051551/