string.IsNullOrEmpty使用Trim()

Bra*_*yce 5 c# string trim isnullorempty

我想删除第一行:

                 !string.IsNullOrEmpty(cell.Text) 
Run Code Online (Sandbox Code Playgroud)

这会引起任何问题吗?

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

                if ((id % 2 == 0)
                    && !string.IsNullOrEmpty(cell.Text)
                    && !string.IsNullOrEmpty(cell.Text.Trim())
                    )
Run Code Online (Sandbox Code Playgroud)

我认为第一个string.IsNullOrEmpty会在带空格的字符串上返回false,
而Trim()的行会处理它,所以第一个IsNullOrEmpty是无用的

但是在我删除没有修剪的线之前我以为我会被小组运行它.

jco*_*ctx 12

如果cell.Text为null,则没有第一次检查就会出现异常.

  • 如果cell是TextBox,则该属性永远不会为null. (3认同)

Dar*_*rov 8

在.NET 4.0中:

if (id % 2 == 0 && !string.IsNullOrWhiteSpace(cell.Text))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

在旧版本中,您应该保留这两个测试,因为如果您删除第一个并且cell.Text为null,那么当您尝试.Trim在空实例上调用时,您将在第二个上获得NRE .

或者你也可以这样做:

if (id % 2 == 0 && string.IsNullOrWhiteSpace((cell.Text ?? string.Empty).Trim()))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

甚至更好,您可以为字符串类型编写一个扩展方法来执行此操作,以便您可以简单地:

if (id % 2 == 0 && !cell.Text.IsNullOrWhiteSpace())
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

这看起来像这样:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        return string.IsNullOrEmpty((value ?? string.Empty).Trim());
    }
}
Run Code Online (Sandbox Code Playgroud)


Ken*_*rey 5

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

但是,有更好的方法:

if ((id % 2 == 0) && !string.IsNullOrWhiteSpace(cell.Text))
Run Code Online (Sandbox Code Playgroud)

  • 仅在.NET Framework 4和更高版本中可用。 (3认同)