Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用async方法返回值时如何返回值。我犯了一个错误_C#_Api_Asynchronous_Async Await - Fatal编程技术网

C# 使用async方法返回值时如何返回值。我犯了一个错误

C# 使用async方法返回值时如何返回值。我犯了一个错误,c#,api,asynchronous,async-await,C#,Api,Asynchronous,Async Await,我得到的错误在return语句的最后一行 “无法将类型'System.Threading.Tasks.Task'隐式转换为RestSharp.IRestResponse'。存在显式转换(是否缺少强制转换?)” public static async Task ExecuteAsyncRequest(此RestClient客户端,IRestRequest请求),其中T:class,new()//因为我们使用了T。我们需要指定T是class类型还是new类型 { var taskCompletion

我得到的错误在return语句的最后一行

“无法将类型'System.Threading.Tasks.Task'隐式转换为RestSharp.IRestResponse'。存在显式转换(是否缺少强制转换?)”

public static async Task ExecuteAsyncRequest(此RestClient客户端,IRestRequest请求),其中T:class,new()//因为我们使用了T。我们需要指定T是class类型还是new类型
{
var taskCompletionSource=新的taskCompletionSource();
client.ExecuteAsync(请求、重新响应=>
{
//详细的错误信息
if(resresponse.ErrorException!=null)
{
const string message=“检索响应时出错。”;
抛出新的ApplicationException(消息、restResponse.ErrorException);
}
//设置执行的结果
taskCompletionSource.SetResult(Response);
});
//把钱还给我们
返回wait taskCompletionSource.Task;

我不能完全重现这一点:我得到了一个稍微不同的错误

无法将类型“RestSharp.IRestResponse”隐式转换为“RestSharp.IRestResponse”。存在显式转换(是否缺少强制转换?)

这是因为您的方法返回一个
IRestResponse
,但您的
TaskCompletionSource
仅包含一个
IRestResponse
。您可以通过将其更改为
TaskCompletionSource
来修复错误

var taskCompletionSource=new taskCompletionSource();
public static async Task<IRestResponse<T>> ExecuteAsyncRequest<T>(this RestClient client, IRestRequest request) where T : class, new() //Since we used the T. We need to specify wether T is of type class or new type
     {

         var taskCompletionSource = new TaskCompletionSource<IRestResponse>();


         client.ExecuteAsync<T>(request, restResponse =>
         {
             //Verbose message of the error
             if (restResponse.ErrorException != null)
             {

                 const string message = "Error retrieving response.";
                 throw new ApplicationException(message, restResponse.ErrorException);

             }

             //Setting the result of the execution
             taskCompletionSource.SetResult(restResponse);

         });

         //return us the reuslt
         return await taskCompletionSource.Task; 
var taskCompletionSource = new TaskCompletionSource<IRestResponse<T>>();