避免在SortedDictionary C#中重复代码

时间:2016-06-19 12:37:52

标签: c# asp.net asp.net-mvc code-duplication

所以我有两个如果处理字典值。如果方法是POST我只需要将status参数添加到字典中。所有其他参数都是相同的。

var stringBuilder = new StringBuilder();                    
var dictionary = new SortedDictionary<string, string>();
if (method == "GET")
{
    stringBuilder.Append("GET&");
    stringBuilder.Append(Uri.EscapeDataString(url));
    stringBuilder.Append("&");
    dictionary = new SortedDictionary<string, string>
    {
        { "oauth_version" , oauthVersion },
        { "oauth_consumer_key", consumerKey },
        { "oauth_nonce" , oauthNonce },
        { "oauth_signature_method" , oauthSignatureMethod },
        { "oauth_timestamp" , oauthTimeStamp },
        { "oauth_token" , accessToken },
    };
}

if (method == "POST")
{
    stringBuilder.AppendFormat("POST&{0}&", Uri.EscapeDataString(url));
    dictionary = new SortedDictionary<string, string>
    {
        { "oauth_version" , oauthVersion },
        { "oauth_consumer_key", consumerKey },
        { "oauth_nonce" , oauthNonce },
        { "oauth_signature_method" , oauthSignatureMethod },
        { "oauth_timestamp" , oauthTimeStamp },
        { "oauth_token" , accessToken },
        { "status" , status }
    };
}

反正在我的代码中是否有任何重复。任何建议都会很方便。

请注意。

1 个答案:

答案 0 :(得分:2)

我不太了解您的StringBuilder实例变量与您正在构建的字典之间的任何关系,因此假设字典代码重复,可以从那些{{1}中取出条件然后你可以处理剩余的if实例:

StringBuilder

所以基本上在这段代码执行后,你问题中显示的var stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("{0}&{1}&", method, Uri.EscapeDataString(url)); var dictionary = new SortedDictionary<string, string> { { "oauth_version", oauthVersion }, { "oauth_consumer_key", consumerKey }, { "oauth_nonce", oauthNonce }, { "oauth_signature_method", oauthSignatureMethod }, { "oauth_timestamp", oauthTimeStamp }, { "oauth_token", accessToken }, }; if (method == "POST") { // Only add the status parameter if the method is POST dictionary["status"] = status; } stringBuilder个实例变量都会有预期值。

这就是说,你的字典看起来好像它包含查询字符串参数值。如果是这种情况,那么在考虑通过HTTP协议发送它们之前,你肯定会想要正确地对这些值进行url编码:

dictionary
相关问题