我有两节课:
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()
?
将您的
Main
方法标记为 async
之一(自 C# 7.1 起可用)并在 await
上调用 GetCatFact
(或者 getEmployeeData
你的问题有点不一致):
static async Task Main(string[] args)
{
Employee employee = await GetCatFact(); // or getEmployeeData
}
相关:
getEmployeeData
是异步方法,所以你需要等待结果:
var employeeData = await getEmployeeData();
还有另一种选择
var employeeData = getEmployeeData().Result;