为什么NameValueCollection的行为不同?

问题描述 投票:1回答:1
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的行为不同。

c# asp.net namevaluecollection
1个回答
3
投票

HttpUtility.ParseQueryString的情况下,返回类HttpValueCollection的实例(source)继承自NameValueCollection。显然,这个类有意义地覆盖了ToString而不是从对象继承NameValueCollectionToString,因此只是覆盖了完整类型的名称。

ParseQueryString没有提到,因为HttpValueCollectioninternal。他们不希望您使用此类型,您不应该依赖此类型返回。

这是sourceToStringHttpValueCollection

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.