开发者

HttpValueCollection and NameValueCollection

What is the difference between Htt开发者_如何学编程pValueCollection and NameValueCollection?

If possible please explain with example.

Thanks


NameValueCollection is case sensitive for the keys, HttpValueCollection isn't. Also HttpValueCollection is an internal class that derives from NameValueCollection that you are never supposed to use directly in your code. Another property of HttpValueCollection is that it automatically url encodes values when you add them to this collection.

Here's how to use the HttpValueCollection class:

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());
    }
}


One point that is not obvious in Darin's answer is that NameValueCollection does not override ToString() method, while HttpValueCollection overrides it. This particular property and implicit URL encoding of values makes the latter one a right choice if you want to convert the collection back to query string.

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());  
    }
}

Outputs:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜