HttpValueCollection and NameValueCollection

前端 未结 2 1369
孤独总比滥情好
孤独总比滥情好 2020-12-14 15:21

What is the difference between HttpValueCollection and NameValueCollection?
If possible please explain with example.

Thanks

相关标签:
2条回答
  • 2020-12-14 15:56

    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());
        }
    }
    
    0 讨论(0)
  • 2020-12-14 15:58

    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 讨论(0)
提交回复
热议问题