我定义了一个字符串并按string.IsNullOrEmptyOrWhiteSpace()
进行检查。
但我收到了这个错误:
'string'不包含'IsNullOrEmptyOrWhiteSpace'的定义,并且没有扩展方法'IsNullOrEmptyOrWhiteSpace'可以找到类型'string'的第一个参数(你是否缺少using指令或汇编引用?)D:\ project \ project \ Controllers \ aController.cs 23 24项目
是什么原因?
答案 0 :(得分:74)
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
静态类的命名空间在范围内。
答案 1 :(得分:33)
这是另一种替代实现,只是为了好玩。它可能不会像Darin那样表现得好,但它是LINQ的一个很好的例子:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
return value == null || value.All(char.IsWhiteSpace);
}
}
答案 2 :(得分:7)
也许IsNullOrWhiteSpace
是您要搜索的方法? http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx
答案 3 :(得分:3)
我使用过(在.NET v2.0中):
public static class StringExtensions
{
public static bool IsNullOrEmptyOrWhitespace(this string value)
{
return string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim());
}
}
Trim()
方法将删除所有前导或尾随空格,因此如果您的字符串完全是空格,则它将被缩减为空字符串。
我不能说表现一直是个问题。
答案 4 :(得分:2)
有趣的是,没有人在这里使用Trim功能:
public static class StringExtensions
{
public static bool IsNullOrEmptyOrWhiteSpace(this string value)
{
return string.IsNullOrEmpty(value) ||
ReferenceEquals(value, null) ||
string.IsNullOrEmpty(value.Trim(' '));
}
}
更新:我现在在评论中看到它是出于各种原因而被提议和拒绝的,但如果人们更喜欢简洁而不是效率......
答案 5 :(得分:2)
来自Microsoft的.NET 4 Framework源代码的精确副本,.. \ RefSrc \ Source.Net \ 4.0 \ DEVDIV_TFS \ Dev10 \ Releases \ RTMRel \ ndp \ clr \ src \ BCL \ System \ String.cs \ 1305376 \ String.cs
public static bool IsNullOrEmpty(String value) {
return (value == null || value.Length == 0);
}
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;
}
(来自http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx)
IsNullOrWhiteSpace
是一种方便的方法,类似于以下代码,但它提供了卓越的性能:
return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
空白字符由Unicode标准定义。 IsNullOrWhiteSpace
方法解释在将Char.IsWhiteSpace
方法作为空格字符传递给{{1}}方法时返回值为true的任何字符。
答案 6 :(得分:0)
Pre .NET 4.0,最短的:
public static bool IsNullOrWhiteSpace(this string value)
{
return value == null || value.Trim() == "";
}
效率不高;考虑到可读性和性能,Jon更好。