为什么 NameValueCollection 的行为不同?

Why behavior of NameValueCollection is different?

NameValueCollection x = new NameValueCollection(Request.QueryString);
string x1 = x.ToString();
NameValueCollection y = HttpUtility.ParseQueryString(Request.QueryString.ToString());
string y1 = y.ToString();

当我执行上面的代码时,x1 和 y1 的值变成

x1="System.Collections.Specialized.NameValueCollection"
y1="abc=1&xyz=2"   //url pass to controller is 'localhost/first/getresult/?abc=1&xyz=2'

我不明白为什么x1 and y1 is different的价值。我检查了 ParseQueryString() 的文档,它显示它 return NameValueCollection 而我没有得到任何其他信息。

所以,我不明白为什么 xy 的行为不同。

如果 HttpUtility.ParseQueryString an instance of the class HttpValueCollection is returned(source) 继承自 NameValueCollection。显然这个类有意义地覆盖 ToString 而不是 NameValueCollection 从对象继承 ToString,因此只显示全类型名称。

ParseQueryString 中没有提及,因为 HttpValueCollectioninternal。他们不希望你使用这种类型,你不应该依赖这种类型被返回。

这是 HttpValueCollectionToStringsource

public override String ToString() {
    return ToString(true);
}

internal virtual String ToString(bool urlencoded) {
    return ToString(urlencoded, null);
}

internal virtual String ToString(bool urlencoded, IDictionary excludeKeys) {
    int n = Count;
    if (n == 0)
        return String.Empty;

    StringBuilder s = new StringBuilder();
    String key, keyPrefix, item;
    bool ignoreViewStateKeys = (excludeKeys != null && excludeKeys[Page.ViewStateFieldPrefixID] != null);

    for (int i = 0; i < n; i++) {
        key = GetKey(i);

        // Review: improve this... Special case hack for __VIEWSTATE#
        if (ignoreViewStateKeys && key != null && key.StartsWith(Page.ViewStateFieldPrefixID, StringComparison.Ordinal)) continue;
        if (excludeKeys != null && key != null && excludeKeys[key] != null)
            continue;
        if (urlencoded)
            key = UrlEncodeForToString(key);
        keyPrefix = (key != null) ? (key + "=") : String.Empty;

        string[] values = GetValues(i);

        if (s.Length > 0)
            s.Append('&');

        if (values == null || values.Length == 0) {
            s.Append(keyPrefix);
        }
        else if (values.Length == 1) {
            s.Append(keyPrefix);
            item = values[0];
            if (urlencoded)
                item = UrlEncodeForToString(item);
            s.Append(item);
        }
        else {
            for (int j = 0; j < values.Length; j++) {
                if (j > 0)
                    s.Append('&');
                s.Append(keyPrefix);
                item = values[j];
                if (urlencoded)
                    item = UrlEncodeForToString(item);
                s.Append(item);
            }
        }
    }

    return s.ToString();
}