获取'IsNullOrWhiteSpace'的错误

hud*_*hab -1 c# asp.net

我使用了下面这样的代码

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        if (string.IsNullOrWhiteSpace(Request.QueryString["tx"]) == false)
        {
            if (Regex.IsMatch(HttpUtility.UrlDecode(Request.QueryString["tx"]), "[^a-zA-Z0-9 %  +]"))
            {
                //error
                Response.Redirect("Error.aspx");
            }
            else
            {
                SearchResult();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我收到了错误

if(string.IsNullOrWhiteSpace(Request.QueryString ["tx"])== false)

因为 'string'不包含'IsNullOrWhiteSpace'的定义

另外,我也使用了相关的命名空间.

我使用的是asp.net 2.0版,无法改变.请帮助解决此问题需要做些什么

ror*_*.ap 9

String.IsNullOrWhiteSpace 在.NET 4.0中引入:

https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace%28v=vs.100%29.aspx

如果你真的不能使用更高版本,那么你可以构建自己的方法来做同样的事情.

以下是该方法的实现(感谢Farhad Jabiyev):

http://referencesource.microsoft.com/#mscorlib/system/string.cs,55e241b6143365ef

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;
}
Run Code Online (Sandbox Code Playgroud)

注意:我已经删除了[Pure]上述链接中实现中存在的属性,因为System.Diagnostics.Contracts.PureAttribute 在.NET 4.0之前也不存在该属性.

  • @FarhadJabiyev - 谢谢,我试着看一下,但我的连接很不稳定:)我已经更新了我的答案. (2认同)