HttpValueCollection
和NameValueCollection
之间有什么区别?
如果可能,请举例说明。
由于
答案 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¶m2=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¶m2=value2
System.Collections.Specialized.NameValueCollection