7

我想删除第一行:

                 !string.IsNullOrEmpty(cell.Text) 

这会引起任何问题吗?

我在一些代码中遇到了这个:

                if ((id % 2 == 0)
                    && !string.IsNullOrEmpty(cell.Text)
                    && !string.IsNullOrEmpty(cell.Text.Trim())
                    )

我认为第一个 string.IsNullOrEmpty 会在带有空格的字符串上返回 false
并且带有 Trim() 的行会处理这个问题,所以第一个 IsNullOrEmpty 是没用的

但在我删除没有修剪的线之前,我想我会由小组来运行它。

4

9 回答 9

12

如果 cell.Text 为 null,则如果没有第一次检查,您将遇到异常。

于 2012-03-14T17:52:43.603 回答
8

在 .NET 4.0 中:

if (id % 2 == 0 && !string.IsNullOrWhiteSpace(cell.Text))
{
    ...
}

在旧版本中,您应该保留这两个测试,因为如果您删除第一个并且cell.Text为空,那么当您尝试.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());
    }
}
于 2012-03-14T17:53:17.723 回答
7

第一个 IsNullOrEmpty 在使用 Trim() 抛出 NullReferenceException 之前捕获空值。

但是,有一个更好的方法:

if ((id % 2 == 0) && !string.IsNullOrWhiteSpace(cell.Text))
于 2012-03-14T17:54:41.943 回答
1

您可以使用这样的扩展方法:

/// <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;
}
于 2016-09-08T10:37:13.417 回答
0

我相信测试是首先确保 cell.text 不为空......如果是这样,试图绕过它并获得 cell.text.trim() 会窒息,因为你不能对空字符串进行修剪。

于 2012-03-14T17:53:45.233 回答
0

为什么不使用!string.IsNullOrWhitespace(call.Text)和删除前两个检查?

于 2012-03-14T17:54:05.850 回答
0

您不能只删除第一个 IsNullOrEmpty,因为 cell.Text 可能为 null,因此在其上调用 Trim 会引发异常。如果您使用的是 .Net 4.0,请使用IsNullOrWhiteSpace或保留这两项检查。

if ((id % 2 == 0) && !string.IsNullOrWhiteSpace(cell.Text))
于 2012-03-14T17:54:16.643 回答
0

如果 cell.Text 为空,则表达式 string.IsNullOrEmpty(cell.Text.Trim()) 将抛出异常,因为它试图在单元格上运行方法 Trim()。

如果条件是: cell.Text!=null && cell.Text.Trim()!=""

于 2012-03-14T17:54:33.003 回答
0

我们可以使用空条件:

!string.IsNullOrEmpty(cell?.Text?.Trim())

笔记 ”?” 在阅读下一个属性和修剪之前。

于 2022-01-04T15:23:16.537 回答