我定义了一个字符串并通过 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/