c# - 缺少 IsNullOrEmptyOrWhiteSpace 方法

标签 c# .net

我定义了一个字符串并通过 string.IsNullOrEmptyOrWhiteSpace() 检查它。

但是我得到了这个错误:

'string' does not contain a definition for 'IsNullOrEmptyOrWhiteSpace' and no extension method 'IsNullOrEmptyOrWhiteSpace' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) D:\project\project\Controllers\aController.cs 23 24 project

这是什么原因?

最佳答案

String.IsNullOrWhiteSpace已在 .NET 4 中引入。如果您不以 .NET 4 为目标,您可以轻松编写自己的:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(string value)
    {
        if (value != null)
        {
            for (int i = 0; i < value.Length; i++)
            {
                if (!char.IsWhiteSpace(value[i]))
                {
                    return false;
                }
            }
        }
        return true;
    }
}

可以这样使用:

bool isNullOrWhiteSpace = StringExtensions.IsNullOrWhiteSpace("foo bar");

或作为 extension method如果您愿意:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        if (value != null)
        {
            for (int i = 0; i < value.Length; i++)
            {
                if (!char.IsWhiteSpace(value[i]))
                {
                    return false;
                }
            }
        }
        return true;
    }
}

它允许您直接使用它:

bool isNullOrWhiteSpace = "foo bar".IsNullOrWhiteSpace();

要使扩展方法起作用,请确保定义了 StringExtensions 静态类的 namespace 在范围内。

关于c# - 缺少 IsNullOrEmptyOrWhiteSpace 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3174152/

相关文章:

c# - 为什么我更喜欢枚举而不是具有常量值的结构

c# - NuGet 以代码 -1 退出 - 结果构建失败

javascript - 如何从aspx页面重定向到另一个aspx页面中的方法

C# 正则表达式 : How to extract a collection

c# - System.Diagnostics.Process - Del 命令

c# - 赢11 : Pin Unpin a shortcut programmatically using C#

c# - Windows 8 - 在被拒绝后请求相机权限

c# - 无法单击 jquery 对话框中的 asp.net 按钮

c# - yield 返回 vs Lazy<T>

c# - 为什么一个程序集必须被引用两次?