[英]Is it possible to have C# async method return type to be something not Task<T> or void?
[英]The return type of an async method must be void, Task or Task<T> in C#
我有以下方法,並收到以下錯誤。 我想知道如何在這個問題上克服。
異步方法的返回類型必須為空,任務或任務
private static async T GoRequest<T>(string url, Dictionary<string, object> parameters, HttpMethod method,string body = "")
where T : class
{
// the rest of the code I commented.
// the following is the return
var jsonResult = content.Replace(@"\", "").Trim('"');
return typeof (T) == typeof (string)
? jsonResult as T
: JsonConvert.DeserializeObject<T>(jsonResult);
}
您需要將返回類型包裝在Task
。
private static async Task<T> GoRequest<T>(string url, Dictionary<string, object> parameters, HttpMethod method, string body = "")
where T : object
規則很簡單:如果您的“常規”同步方法將返回T
,則async
方法必須返回Task<T>
:
private static async Task<T> GoRequest<T>(string url, Dictionary<string, object> parameters, HttpMethod method,string body = "")
where T : class
您無需進行任何其他更改:當async
代碼返回T
,編譯器將確保結果實際上是Task<T>
。
注意:由於您的async
方法中沒有await
,您最好將其更改為“常規”的同步方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.