IsNullOrEmpty和IsNullOrWhiteSpace的区别

IsNullOrEmpty

// string
/// <summary>Indicates whether the specified string is null or an <see cref="F:System.String.Empty" /> string.</summary>
/// <param name="value">The string to test. </param>
/// <returns>true if the <paramref name="value" /> parameter is null or an empty string (""); otherwise, false.</returns>
[__DynamicallyInvokable]
public static bool IsNullOrEmpty(string value)
{
    return value == null || value.Length == 0;
}

IsNullOrWhiteSpace

// string
/// <summary>Indicates whether a specified string is null, empty, or consists only of white-space characters.</summary>
/// <param name="value">The string to test.</param>
/// <returns>true if the <paramref name="value" /> parameter is null or <see cref="F:System.String.Empty" />, or if <paramref name="value" /> consists exclusively of white-space characters. </returns>
[__DynamicallyInvokable]
public static bool IsNullOrWhiteSpace(string value)
{
    if (value == null)
    {
        return true;
    }
    for (int i = 0; i < value.Length; i++)
    {
        if (!char.IsWhiteSpace(value[i]))
        {
            return false;
        }
    }
    return true;
}

后者比前者更严谨,指示指定的字符串是 null、空还是仅由空白字符组成。

猜你喜欢

转载自www.cnblogs.com/tanfuchao/p/9073308.html