c# - 创建通用异步任务函数

标签 c# generics asp.net-web-api system.net.httpwebrequest

我创建了一个使用async/await 返回对象的函数。我想使该函数通用,以便它可以返回我传入的任何对象。代码是样板,除了要返回的对象。我希望能够调用 GetAsync 并让它返回正确的对象

public Patron getPatronById(string barcode)
{
    string uri = "patrons/find?barcode=" + barcode;
    Patron Patron =  GetAsync(uri).Result;
    return Patron;
}

private async Task<Patron> GetAsync(string uri)
{
    var client = GetHttpClient(uri);
    var content = await client.GetStringAsync(uri);
    JavaScriptSerializer ser = new JavaScriptSerializer();
    Patron Patron = ser.Deserialize<Patron>(content);
    return Patron;
}

最佳答案

泛型方法呢?

private async Task<T> GetAsync<T>(string uri)
{
    var client = GetHttpClient(uri);
    var content = await client.GetStringAsync(uri);
    var serializer = new JavaScriptSerializer();
    var t = serializer.Deserialize<T>(content);
    return t;
}

通常,您应该将此方法放在另一个类中并使其成为public,以便它可以被不同类中的方法使用。

关于调用此方法的方式,您可以尝试以下方式:

 // I capitalized the first letter of the method, 
 // since this is a very common convention in .NET
 public Patron GetPatronById(string barcode)
 {
     string uri = "patrons/find?barcode=" + barcode;
     var Patron =  GetAsync<Patron>(uri).Result;
     return Patron;
 }

注意:在上面的代码片段中,我假设您没有将 GetAsync 移动到另一个类中。如果你移动它,那么你必须做一个微小的改变。

更新

I'm not following what you mean by your note. Do I need to make GetPatronById a task function as well - like Yuval has done below?

我的意思是这样的:

// The name of the class may be not the most suitable in this case.
public class Repo
{
    public static async Task<T> GetAsync<T>(string uri)
    {
        var client = GetHttpClient(uri);
        var content = await client.GetStringAsync(uri);
        var serializer = new JavaScriptSerializer();
        var t = serializer.Deserialize<T>(content);
        return t;
    }
}

public Patron GetPatronById(string barcode)
{
     string uri = "patrons/find?barcode=" + barcode;
     var Patron =  Repo.GetAsync<Patron>(uri).Result;
     return Patron;
}

关于c# - 创建通用异步任务函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235676/

相关文章:

c# - LINQ - 按最后一位数字连接两个列表

Azure Web API 数据库用户导入和密码哈希

c# - 为什么我的区域特定 Web API 可以从所有其他区域访问?

c# - Linq2Twitter - 什么是 OAuthToken?

c# - 在 .Net 应用程序中包含单元测试时的设计注意事项?

c# - 在 WPF 中的 View 模型上应用模板样式

c++ - 在容器中存储模板化派生类

haskell - 为什么没有办法在 Haskell 中推导出 Applicative Functor?

c# - 在 Ninject 中寻找通用接口(interface)的具体实现

c# - 任何人都可以向我解释 CreatedAtRoute() 吗?