我创建了一个使用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/