C# 将keyvaluepair传递到方法中
我试图将一个键值对传递给一个方法,但是在方法签名中得到了一个关于IEnumerable的类型不匹配。我没有正确初始化键值对吗C# 将keyvaluepair传递到方法中,c#,C#,我试图将一个键值对传递给一个方法,但是在方法签名中得到了一个关于IEnumerable的类型不匹配。我没有正确初始化键值对吗 KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>("token", "abcdefg"); HttpResponseMessage tokenResponse = PostFormUr
KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>("token", "abcdefg");
HttpResponseMessage tokenResponse =
PostFormUrlEncoded<HttpResponseMessage> (keyValuePair);
public static async Task<TResult> PostFormUrlEncoded<TResult>(
IEnumerable<KeyValuePair<string, string>> postData)
{
//calling FormUrlEncodedContent(postData)
}
KeyValuePair KeyValuePair=新的KeyValuePair(“令牌”、“abcdefg”);
HttpResponseMessage令牌响应=
PostFormUrlEncoded(keyValuePair);
公共静态异步任务PostFormUrlEncoded(
IEnumerable postData)
{
//调用FormUrlEncodedContent(postData)
}
这样做:
KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>("token", "abcdefg");
public static async Task<TResult> PostFormUrlEncoded<TResult>(
KeyValuePair<string, string> postData)
{
...
}
KeyValuePair KeyValuePair=新的KeyValuePair(“令牌”、“abcdefg”);
公共静态异步任务PostFormUrlEncoded(
KeyValuePair(postData)
{
...
}
如果您的方法应该接受KeyValuePair
对的集合,则使用
var keyValuePairs = new[] { new KeyValuePair<string, string>("token", "abcdefg") };
HttpResponseMessage tokenResponse = await PostFormUrlEncoded<HttpResponseMessage>(keyValuePairs);
我认为您需要3个修复:
- 添加等待
- 传递集合,而不是单个对象
- 将Post方法重命名为
——这不是严格需要的,而是良好的实践PostFormUrlEncoded*Async*
var keyValuePair=新的keyValuePair(“token”、“abcdefg”);
HttpResponseMessageTokenResponse=wait//Fix 1
PostFormUrlEncodedAsync(新[]{keyValuePair});//修正案2和3
IEnumerable
是键值对的集合,而您的keyValuePair
是单个键值对。另外,请在尝试将内容传递到PostFormUrlEncoded
的位置添加代码。刚才添加了callIt必须接受集合的方法。但是方法调用不是这样工作的。System.Threading.Task.Task和System.Net.Http之间不匹配。HttpResponseMessage@John您是否添加了等待<代码>等待PostFormUrlEncoded(keyValuePairs)代码>它不是异步方法。它是。请参阅您的问题:公共静态异步任务
-这意味着您声明了异步方法。如果不应该,那么将其更改为publicstatictresult
我怎么知道?你没有展示那种方法的主体!这似乎是另一个问题。如果你有新问题,请点击按钮提问。如果此问题有助于提供上下文,请包含指向此问题的链接
public static async Task<TResult> PostFormUrlEncoded<TResult>(KeyValuePair<string, string> postData)