否定了空合并运算符 [英] Negate the null-coalescing operator
问题描述
我有一堆的字符串,我需要上使用.Trim(),但他们可以为null。这将是更加简洁,如果我可以做这样的事情:
I have a bunch of strings I need to use .Trim() on, but they can be null. It would be much more concise if I could do something like:
string endString = startString !?? startString.Trim();
基本上退回一部分的权利,如果左边的部分是不为空,否则只返回空值。我刚刚结束了使用三元运算符,但反正是有使用空合并运算符用于此目的?
Basically return the part on the right if the part on the left is NOT null, otherwise just return the null value. I just ended up using the ternary operator, but is there anyway to use the null-coalescing operator for this purpose?
推荐答案
您可以创建返回时它会尝试修剪值空
的扩展方法。
You could create an extension method which returns null
when it tries to trim the value.
public String TrimIfNotNull(this string item)
{
if(String.IsNullOrEmpty(item))
return item;
else
return item.Trim();
}
请注意你不能将其命名为修剪,因为扩展方法不能覆盖实例方法。
Note you can't name it Trim because extension methods can't override instance methods.
这篇关于否定了空合并运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!