我定义一个字符串并检查它string.IsNullOrEmptyOrWhiteSpace().
但我得到了这个错误:
'string'不包含'IsNullOrEmptyOrWhiteSpace'的定义,并且没有扩展方法'IsNullOrEmptyOrWhiteSpace'可以找到类型'string'的第一个参数(你是否缺少using指令或汇编引用?)D:\ project\project\Controllers\aController.cs 23 24项目
是什么原因?
Dar*_*rov 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;
}
}
Run Code Online (Sandbox Code Playgroud)
可以像这样使用:
bool isNullOrWhiteSpace = StringExtensions.IsNullOrWhiteSpace("foo bar");
Run Code Online (Sandbox Code Playgroud)
或者如果您愿意,可以作为扩展方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
允许您直接使用它:
bool isNullOrWhiteSpace = "foo bar".IsNullOrWhiteSpace();
Run Code Online (Sandbox Code Playgroud)
要使扩展方法起作用,请确保StringExtensions已定义静态类的命名空间在范围内.
Jon*_*eet 33
这是另一种替代实现,只是为了好玩.它可能不会像Darin那样表现得好,但它是LINQ的一个很好的例子:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
return value == null || value.All(char.IsWhiteSpace);
}
}
Run Code Online (Sandbox Code Playgroud)
也许IsNullOrWhiteSpace你正在寻找的方法?http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx
| 归档时间: |
|
| 查看次数: |
15686 次 |
| 最近记录: |