jri*_*ggs 2 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;
}
Run Code Online (Sandbox Code Playgroud)
通用方法怎么样?
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;
}
Run Code Online (Sandbox Code Playgroud)
通常,您应该将此方法放入另一个类并创建它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;
}
Run Code Online (Sandbox Code Playgroud)
注意:在上面的代码片段中,我假设您没有移动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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2711 次 |
| 最近记录: |