泛型方法呢?
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
移到另一个类中。如果你移动它,那么你必须做一些微小的改变。
更新
我没有按照您的说明理解您的意思。我是否也需要让 GetPatronById 成为一个任务函数——就像 Yuval 在下面所做的那样?
我的意思是这样的:
// 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;
}