避免在 SortedDictionary C# 中重复代码

Avoid duplicate code in SortedDictionary C#

所以我有两个 if 语句来处理字典 value.If 方法是 POST 我只需要将 status 参数添加到 dictionary.All 其他参数是一样。

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 }
    };
}

我的code.Any建议中是否有避免重复的方法?

敬请谅解。

我看不出你的 StringBuilder 实例变量和你正在构建的字典之间有什么关系,所以假设字典代码重复,它可以从那些 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;
}

所以基本上在这段代码执行之后,stringBuilderdictionary 实例变量如您的问题所示将具有预期值。

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

var dictionary = new SortedDictionary<string, string>
{
    { "oauth_version", Uri.EscapeDataString(oauthVersion) },
    { "oauth_consumer_key", Uri.EscapeDataString(consumerKey) },
    { "oauth_nonce", Uri.EscapeDataString(oauthNonce) },
    { "oauth_signature_method", Uri.EscapeDataString(oauthSignatureMethod) },
    { "oauth_timestamp", Uri.EscapeDataString(oauthTimeStamp) },
    { "oauth_token", Uri.EscapeDataString(accessToken) },
};

if (method == "POST")
{
    // Only add the status parameter if the method is POST
    dictionary["status"] = Uri.EscapeDataString(status);
}