这似乎是在HttpContext.Request.Form的toString()方法装饰所以结果是不同的 从的ToString一个()返回直接在NameValueCollection中whencalled:
It seems like the ToString () in HttpContext.Request.Form is decorated so the result is different from the one returned from ToString() whencalled directly on a NameValueCollection:
NameValueCollection nameValue = Request.Form;
string requestFormString = nameValue.ToString();
NameValueCollection mycollection = new NameValueCollection{{"say","hallo"},{"from", "me"}};
string nameValueString = mycollection.ToString();
return "RequestForm: " + requestFormString + "<br /><br />NameValue: " + nameValueString;
结果如下:
RequestForm:都说=你好&放大器;从=我
RequestForm: say=hallo&from=me
NameValue:System.Collections.Specialized.NameValueCollection
NameValue: System.Collections.Specialized.NameValueCollection
如何才能得到字符串NameValueString = mycollection.ToString();返回之称=你好&放大器;从=我?
How can I get "string NameValueString = mycollection.ToString();" to return "say=hallo&from=me"?
您没有看到很好地格式化输出的原因是因为的Request.Form
实际上是一个类型的 System.Web.HttpValueCollection
。此类重写的ToString()
,使其返回所需的文本。标准的NameValueCollection
做的没有的覆盖的ToString()
,所以你得到的输出在对象
版本。
The reason you don't see the nicely formatted output is because Request.Form
is actually of type System.Web.HttpValueCollection
. This class overrides ToString()
so that it returns the text you want. The standard NameValueCollection
does not override ToString()
, and so you get the output of the object
version.
如果无法访问类的特殊版本,你需要自己遍历集合,并建立字符串:
Without access to the specialized version of the class, you'll need to iterate the collection yourself and build up the string:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mycollection.Count; i++)
{
string curItemStr = string.Format("{0}={1}", mycollection.Keys[i],
mycollection[mycollection.Keys[i]]);
if (i != 0)
sb.Append("&");
sb.Append(curItemStr);
}
string prettyOutput = sb.ToString();