??合并为空字符串? [英] ?? Coalesce for empty string?
问题描述
我发现自己做的越来越多的事情是检查字符串是否为空(如""
或null)和条件运算符.
Something I find myself doing more and more is checking a string for empty (as in ""
or null) and a conditional operator.
当前示例:
s.SiteNumber.IsNullOrEmpty() ? "No Number" : s.SiteNumber;
这只是扩展方法,等效于:
This is just an extension method, it's equivalent to:
string.IsNullOrEmpty(s.SiteNumber) ? "No Number" : s.SiteNumber;
由于它为空且不为null,因此??
不会解决问题. ??
的string.IsNullOrEmpty()
版本将是理想的解决方案.我在想必须有一种更清洁的方法(我希望!),但是我一直茫然地找不到它.
Since it's empty and not null, ??
won't do the trick. A string.IsNullOrEmpty()
version of ??
would be the perfect solution. I'm thinking there has to be a cleaner way of doing this (I hope!), but I've been at a loss to find it.
有人知道有更好的方法吗,即使仅在.Net 4.0中也是如此?
Does anyone know of a better way to do this, even if it's only in .Net 4.0?
推荐答案
没有内置的方法可以做到这一点.您可以使扩展方法返回字符串或null,但这将允许合并运算符起作用.但是,这很奇怪,我个人更喜欢您当前的方法.
There isn't a built-in way to do this. You could make your extension method return a string or null, however, which would allow the coalescing operator to work. This would be odd, however, and I personally prefer your current approach.
由于您已经在使用扩展方法,为什么不制作一个返回值或默认值的扩展方法呢?
Since you're already using an extension method, why not just make one that returns the value or a default:
string result = s.SiteNumber.ConvertNullOrEmptyTo("No Number");
这篇关于??合并为空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!