我发现自己越来越多地在检查字符串是否为空(如在""或null中)和条件运算符。
当前示例:
s.SiteNumber.IsNullOrEmpty() ? "No Number" : s.SiteNumber;这只是一个扩展方法,它等同于:
string.IsNullOrEmpty(s.SiteNumber) ? "No Number" : s.SiteNumber;因为它是空的并且不是null,所以??不会这样做。??的string.IsNullOrEmpty()版本将是完美的解决方案。我在想,一定有一种更干净的方式来做这件事(我希望!),但我一直在迷茫地寻找它。
有没有人知道更好的方法,即使是在.Net 4.0中也是如此?
发布于 2014-01-29 03:37:37
我喜欢下面的扩展方法QQQ的简洁性,当然,像这样的操作符?那就更好了。但我们可以通过不只是两个而是三个字符串选项值的比较来实现这一点,这其中一个需要时不时地处理(参见下面的第二个函数)。
#region QQ
[DebuggerStepThrough]
public static string QQQ(this string str, string value2)
{
return (str != null && str.Length > 0)
? str
: value2;
}
[DebuggerStepThrough]
public static string QQQ(this string str, string value2, string value3)
{
return (str != null && str.Length > 0)
? str
: (value2 != null && value2.Length > 0)
? value2
: value3;
}
// Following is only two QQ, just checks null, but allows more than 1 string unlike ?? can do:
[DebuggerStepThrough]
public static string QQ(this string str, string value2, string value3)
{
return (str != null)
? str
: (value2 != null)
? value2
: value3;
}
#endregionhttps://stackoverflow.com/questions/2420125
复制相似问题