为什么Request.Form.ToString()的返回值从NameValueCollection.ToString的结果不同() [英] Why is the return value of Request.Form.ToString() different from the result of NameValueCollection.ToString()

查看:500
本文介绍了为什么Request.Form.ToString()的返回值从NameValueCollection.ToString的结果不同()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是在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();

这篇关于为什么Request.Form.ToString()的返回值从NameValueCollection.ToString的结果不同()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆