HttpValueCollection和NameValueCollection

时间:2011-09-22 12:05:29

标签: c#

HttpValueCollectionNameValueCollection之间有什么区别?
如果可能,请举例说明。

由于

2 个答案:

答案 0 :(得分:47)

NameValueCollection区分大小写,HttpValueCollection不是。此外,HttpValueCollection是一个内部类,派生自NameValueCollection,您永远不应该在代码中直接使用它。 HttpValueCollection的另一个属性是,当您将值添加到此集合时,它会自动对URL进行编码。

以下是如何使用HttpValueCollection类:

class Program
{
    static void Main()
    {
        // returns an implementation of NameValueCollection
        // which in fact is HttpValueCollection
        var values = HttpUtility.ParseQueryString(string.Empty);
        values["param1"] = "v&=+alue1";
        values["param2"] = "value2";*

        // prints "param1=v%26%3d%2balue1&param2=value2"
        Console.WriteLine(values.ToString());
    }
}

答案 1 :(得分:4)

Darin的答案中不明显的一点是,NameValueCollection不会覆盖ToString()方法,而HttpValueCollection会覆盖它。如果要将集合转换回查询字符串,则此特定属性和值的隐式URL编码会使后者成为正确的选择。

public class Test
{
    public static void Main()
    {
        var httpValueCollection = HttpUtility.ParseQueryString(string.Empty);
        httpValueCollection["param1"] = "value1";
        httpValueCollection["param2"] = "value2";
        Console.WriteLine(httpValueCollection.ToString());

        var nameValueCollection = new NameValueCollection();
        nameValueCollection["param1"] = "value1";
        nameValueCollection["param2"] = "value2";
        Console.WriteLine(nameValueCollection.ToString());  
    }
}

输出:

param1=value1&param2=value2
System.Collections.Specialized.NameValueCollection