jub*_*ubi 2 .net c# asp.net-mvc-4 .net-core
有没有更好的方法来使用 Null Coalescing 运算符检查字符串是否为空或 null。当我对字符串使用空值而不是 null 时,null Coalescing 运算符无法获得所需的结果。
string x = null;
string y = x ?? "Default Value";
Console.WriteLine(y);
Run Code Online (Sandbox Code Playgroud)
在这里,如果我x = null用x=""这个替换,则不起作用。
如果我使用String.IsNullOrEmpty方法
if(String.IsNullOrEmpty(x)
{
y= "default value"
}
{
y =x
}
Run Code Online (Sandbox Code Playgroud)
我的代码块有多行,我想让它变得简单。您能建议一种更好的方法来保持代码干净简单吗?因为它被用在很多地方。
小智 5
您可以使用?运营商
string x = null;
string y = string.IsNullOrEmpty(x) ? "Default Value" : x;
Console.WriteLine(y);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3224 次 |
| 最近记录: |