如何通过共享方法中的参数填充NameValueCollection?

时间:2013-04-10 17:32:04

标签: c# c#-4.0 query-string argument-passing namevaluecollection

我有一段代码:

var requestMock = new Mock<HttpRequestBase>();
var queryString = new NameValueCollection();
queryString["abc"] = "123";
queryString["qwe"] = "456";
queryString["yui"] = "678";
...
requestMock.SetupGet(rqst => rqst.QueryString).Returns(queryString);

现在,我想将上述段写为方法:

var requestMock = GetRequestMock(???);

我打算发送查询字符串键/值,可以是任何东西。 并且k / v对的数量也可以是任何值。

public Mock<HttpRequestBase> GetRequestMock(???)
{
var requestMock = new Mock<HttpRequestBase>();
....
requestMock.SetupGet(rqst => rqst.QueryString).Returns(queryString);
return requestMock;
}

有效和简单地做到这一点最好的方法是什么?

1 个答案:

答案 0 :(得分:2)

一种方法是使用Dictionary

public Mock<HttpRequestBase> GetRequestMock(Dictionary<string, object> queryParms)
{
    var queryString = new NameValueCollection();
    foreach (KeyValuePair<string, object> kvp in queryParms)
    {
        queryString[kvp.Key] = Convert.ToString(kvp.Value);
    }

    ...
}

然后你可以这样称呼它:

GetRequestMock(new Dictionary<string, object> { { "abc", "123" }, { "qwe", "456" } } );