如何存储从异步方法返回的对象?

问题描述 投票:0回答:2

我有两节课:

    public class Employee
    {
        public string status { get; set; }
        public EmployeeData[] data { get; set; }
        public string message { get; set; }
    }

    public class EmployeeData
    {
        public int id { get; set; }
        public string employee_name { get; set; }
        public int employee_salary { get; set; }
        public int employee_age { get; set; }
        public string profile_image { get; set; }
    }

我正在尝试调用公共 API:

// using Newtonsoft.Json;
// using RestSharp;
public static async Task<Employee> getEmployeeData()
    {
        var client = new RestClient("http://dummy.restapiexample.com/api/v1/"); // Base url
        var request = new RestRequest("employees");
        var response = client.Execute(request);

        Employee result = null;
        string rawResponse = "";
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            rawResponse = response.Content;
            result = JsonConvert.DeserializeObject<Fact>(rawResponse); // JSON to C# Object
        }
        return result ;
    }

然后我尝试将

getEmployeeData()
返回的任何内容存储在 main 内名为
employee
的变量中:

static void Main(string[] args)
    {
        Employee employee = GetCatFact();
    }

但是它说:

“无法将类型‘system.threading.tasks.task’隐式转换为‘Employee’”

那么我该如何制作才能将

getEmployeeData()
存储在变量
employee
中而不更改
getEmployeeData()

c# .net async-await task
2个回答
2
投票

将您的

Main
方法标记为
async
之一(自 C# 7.1 起可用)并在
await
上调用
GetCatFact
(或者
getEmployeeData
你的问题有点不一致):

static async Task Main(string[] args)
{
     Employee employee = await GetCatFact(); // or getEmployeeData
}

相关:

  1. 使用async和await进行异步编程
  2. async
    修饰符
  3. await
    操作员

0
投票

getEmployeeData
是异步方法,所以你需要等待结果:

var employeeData = await getEmployeeData();

还有另一种选择

var employeeData = getEmployeeData().Result;
© www.soinside.com 2019 - 2024. All rights reserved.