重构代码以制作更通用的方法

时间:2018-05-05 21:19:12

标签: c# xamarin xamarin.forms

我想尝试更好地重构这个方法,而我在理解异步时有一些困难我有一个web api2项目,我使用我的数据访问层分享到手机应用程序。我不确定我的语法是否正确我在xamrian表单应用程序中使用xamrian共享库。

我将有各种方法链接获取客户端,这些客户端将具有终点API /客户端,但obv其返回类型将是不同的。

如何使用列表视图说明以下工作。

我如何使用以下方法,然后在sql lite中本地存储作业的一般做法是什么。

public string BaseUrl { get; set; }
public string EndPoint { get; set; }

让我们去看看网络服务并抓住工作清单。

public async List<Job> GetJSON()
{
        List<Job> rootObject = new List<Job>();

        try
        {
            var client = new System.Net.Http.HttpClient();
            var response = await client.GetAsync("http://myinternaliis/api/job");
            string json = await response.Content.ReadAsStringAsync();
             if (json != "")
            {
                rootObject = JsonConvert.DeserializeObject< List<Job>>(json);
            }

        }
        catch (InvalidCastException e)
        {
            throw e;
        }
        return await rootObject;

 }

感谢您帮助我提高理解力。

1 个答案:

答案 0 :(得分:2)

我猜你正在寻找类似的东西:

public async Task<T> GetJson<T>(string url)
{
    using (var client = new System.Net.Http.HttpClient())
    {
        var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();

        return (T)JsonConvert.DeserializeObject<T>(json);
    }
}
通常我有:
IApi - 定义所有API方法
IHttpService - 定义Get,Post等方法 IJsonConverter - 定义序列化和反序列化等方法。

以下是一个例子:

public interface IJsonConverter
{
    T Deserialize<T>(string json);
    string Serialize<T>(T data);
}

public class JsonConveter : IJsonConverter
{
    public T Deserialize<T>(string json) => JsonConvert.DeserializeObject<T>(json);
    public string Serialize<T>(T data) => JsonConvert.Serialize(data);
}

public interface IHttpService
{
    Task<T> Get<T>(string url);
}

public class HttpService : IHttpService
{
    readonly IJsonConverter jsonConverter;

    public HttpService(IJsonConverter jsonConverter)
    {
        this.jsonConverter = jsonConverter;
    }

    public async Task<T> Get<T>(string url)
    {
        using (var client = new System.Net.Http.HttpClient())
        {
            var response = await client.GetAsync(url);
            var json = await response.Content.ReadAsStringAsync();

            return jsonConverter.Deserialize<T>(json);
        }
    }
}

public interface IApi
{
    Task<List<Job>> GetJobs();
}

public class Api : IApi
{
    readonly string url = "http://myinternaliis/api/";
    readonly IHttpService httpService;

    public Api(IHttpService httpService)
    {
        this.httpService = httpService;
    }

    public Task<List<Job>> GetJobs() => httpService.Get<List<Job>>($"{url}job");
}
相关问题