我有很多次输入文字,
如果它是空的(用户没有输入任何文本) - 我想发送到数据库查询"null"
而不是 String.Empty.(或"")
所以我发现自己做了很多这样的事情:
var mySqlValue = string.IsNullOrEmpty( tbCustomerId.Text)?null:tbCustomerId.Text;
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎很难看.
.net为相反的场景提供了许多其他解决方案:
string.IsNullOrEmpty
string.IsNullOrWhiteSpace
myProblemVal ?? myDefultVal
Run Code Online (Sandbox Code Playgroud)
我知道这可以通过扩展方法解决 - 我知道如何做到这一点..
但有什么更好的吗?
是否有任何智能代码:" if its empty -> null".
Bot*_*000 21
您可以使用扩展方法:
public static class Extensions {
public static string NullIfWhiteSpace(this string value) {
if (String.IsNullOrWhiteSpace(value)) { return null; }
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样使用:
var mySqlValue = tbCustomerId.Text.NullIfWhiteSpace();
Run Code Online (Sandbox Code Playgroud)
我真的不知道你想象的东西比扩展方法更好.你如何定义"更好"?短?使用特殊关键字?使用很少使用的运算符看起来很聪明?这只是附加到您的值的单个方法调用,它甚至可以在空值上运行,并且您需要的逻辑不能以比这更短的方式表达.另外,我不知道它的任何特殊语法.
声明自己的静态方法:
public static string NullIfEmpty(string value)
{
return string.IsNullOrEmpty(value) ? null : value;
}
Run Code Online (Sandbox Code Playgroud)
干
MyHelper.NullIfEmpty(value)并不比调用字符串类型的静态方法更糟糕...而且它似乎比每次写入"string.IsNullOrEmpty(tbCustomerId.Text)?null:tbCustomerId.Text"更清晰.