我创建了一个KeyValuePair列表,以将内容填充为HttpClient的数据。

List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();

keyValues.Add(new KeyValuePair<string, string>("email", email));
keyValues.Add(new KeyValuePair<string, string>("password", password));
keyValues.Add(new KeyValuePair<string, string>("plan_id", planId));

var content = new FormUrlEncodedContent(keyValues);


但是后来我发现我必须发送一个int值作为plan_id。如何更改上面的列表以接受KeyValuePair。还是有更好的方法来做到这一点?

最佳答案

使用FormUrlEncodedContent时,使用KeyValuePair<string, object>放置值并将列表创建或转换为KeyValuePair<string, string>

建立新清单

List<KeyValuePair<string, object>> keyValues = new List<KeyValuePair<string, object>>();

keyValues.Add(new KeyValuePair<string, object>("email", "asdasd"));
keyValues.Add(new KeyValuePair<string, object>("password", "1131"));
keyValues.Add(new KeyValuePair<string, object>("plan_id", 123));
keyValues.Add(new KeyValuePair<string, object>("other_field", null));

var content = new FormUrlEncodedContent(keyValues.Select(s =>
    new KeyValuePair<string, string>(s.Key, s.Value != null ? s.ToString() : null)
));


转换清单

public static KeyValuePair<string, string> ConvertRules(KeyValuePair<string, object> kv)
{
    return new KeyValuePair<string, string>(kv.Key, kv.Value != null ? kv.ToString() : null);
}

static Task Main(string[] args)
{
    List<KeyValuePair<string, object>> keyValues = new List<KeyValuePair<string, object>>();

    keyValues.Add(new KeyValuePair<string, object>("email", "asdasd"));
    keyValues.Add(new KeyValuePair<string, object>("password", "1131"));
    keyValues.Add(new KeyValuePair<string, object>("plan_id", 123));
    keyValues.Add(new KeyValuePair<string, object>("other_field", null));

    var content = new FormUrlEncodedContent(keyValues.ConvertAll(ConvertRules)));
));

关于c# - C#如何创建KeyValuePair的通用列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29761979/

10-15 04:42