我需要在C#中使用查询字符串构建一个URL.这样做的最佳方法是什么?现在,我正在使用类似的东西,
string url = String.Format("foo.aspx?{0}={1}&{2}={3}", "a", 123, "b", 456);
Run Code Online (Sandbox Code Playgroud)
有更好的首选方法吗?
我认为这是一个很好的方法,如果它总是知道你有什么参数,如果这是未知的时候你总是可以保持List <KeyValuePair <string,string >>,其中键是名称,值是值,然后使用类似的foreach循环构建查询字符串
StringBuilder sb = new StringBuilder();
foreach(KeyValuePair<string,string> q in theList)
{
// build the query string here.
sb.Append(string.format("{0}={1}&", q.Key, q.Value);
}
Run Code Online (Sandbox Code Playgroud)
注意:代码未经过测试且尚未编译,因此可能无法完全正常工作.