[英]string.IsNullOrEmpty using Trim()
我想删除第一行:
!string.IsNullOrEmpty(cell.Text)
这会导致任何问题吗?
我在一些代码中遇到了这个:
if ((id % 2 == 0)
&& !string.IsNullOrEmpty(cell.Text)
&& !string.IsNullOrEmpty(cell.Text.Trim())
)
我认为第一个 string.IsNullOrEmpty 会在带空格的字符串上返回 false
和 Trim() 的行负责处理,所以第一个 IsNullOrEmpty 没用
但在我删除没有修剪的线之前,我想我应该由小组来运行它。
如果cell.Text为null,则没有第一次检查就会出现异常。
在.NET 4.0中:
if (id % 2 == 0 && !string.IsNullOrWhiteSpace(cell.Text))
{
...
}
在旧版本中,您应该保留两个测试,因为如果删除第一个并且cell.Text
为null,当您尝试在空实例上调用.Trim
时,将在第二个上获得NRE。
或者你也可以这样做:
if (id % 2 == 0 && string.IsNullOrWhiteSpace((cell.Text ?? string.Empty).Trim()))
{
...
}
甚至更好,您可以为字符串类型编写一个扩展方法来执行此操作,以便您可以简单地:
if (id % 2 == 0 && !cell.Text.IsNullOrWhiteSpace())
{
...
}
这看起来像这样:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
return string.IsNullOrEmpty((value ?? string.Empty).Trim());
}
}
第一个IsNullOrEmpty在使用Trim()抛出NullReferenceException之前捕获空值。
但是,有一种更好的方法:
if ((id % 2 == 0) && !string.IsNullOrWhiteSpace(cell.Text))
你可以像这样使用扩展方法:
/// <summary>
/// Indicates whether the specified string is null or empty.
/// This methods internally uses string.IsNullOrEmpty by trimming the string first which string.IsNullOrEmpty doesn't.
/// .NET's default string.IsNullOrEmpty method return false if a string is just having one blank space.
/// For such cases this custom IsNullOrEmptyWithTrim method is useful.
/// </summary>
/// <returns><c>true</c> if the string is null or empty or just having blank spaces;<c>false</c> otherwise.</returns>
public static bool IsNullOrEmptyWithTrim(this string value)
{
bool isEmpty = string.IsNullOrEmpty(value);
if (isEmpty)
{
return true;
}
return value.Trim().Length == 0;
}
我们可以使用 null 条件:
!string.IsNullOrEmpty(cell?.Text?.Trim())
笔记 ”?” 在阅读下一个属性和修剪之前。
我相信测试是为了确保cell.text首先不是null ...如果是这样,试图绕过它并得到只是cell.text.trim()会因为你无法对空字符串进行修剪而窒息。
为什么不使用!string.IsNullOrWhitespace(call.Text)
并删除前两个检查?
你不能只删除第一个IsNullOrEmpty作为cell.Text可能为null,因此在它上面调用Trim将抛出异常。 如果您使用.Net 4.0或使用两个检查,请使用IsNullOrWhiteSpace 。
if ((id % 2 == 0) && !string.IsNullOrWhiteSpace(cell.Text))
如果cell.Text为null,则表达式string.IsNullOrEmpty(cell.Text.Trim())将抛出异常,因为它试图在单元格上运行方法Trim()。
如果条件如下,则更多可读:cell.Text!= null && cell.Text.Trim()!=“”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.