【发布时间】:2014-04-10 22:27:04
【问题描述】:
我在sample from Xamarin 中看到了这种方法,使用 JSON 访问 REST 服务器:
List<Country> countries = new List<Country>();
public Task<List<Country>> GetCountries()
{
return Task.Factory.StartNew (() => {
try {
if(countries.Count > 0)
return countries;
var request = CreateRequest ("Countries");
string response = ReadResponseText (request);
countries = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (response);
return countries;
} catch (Exception ex) {
Console.WriteLine (ex);
return new List<Country> ();
}
});
}
其中“CreateRequest”和“ReadResponseText”是与 REST 服务器交互的方法,基本上接收国家列表以反序列化并在列表中返回。 所以现在,我正在尝试使这个方法成为通用方法,以便接收类型并返回指定类型的对象的通用列表,如下所示:
public static Task<List<Object>> getListOfAnyObject(string requested_object, Type type)
{
return Task.Factory.StartNew (() => {
try {
var request = CreateRequest (requested_object);
string response = ReadResponseText (request);
List<Object> objects = // create a generic list based on the specified type
objects = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Object>> (response); // not sure how to handle this line
return objects;
} catch (Exception ex) {
Console.WriteLine (ex);
return ex.Message;
}
});
}
所以我的问题是,我怎样才能创建上面的方法以便越来越少地使用它(将列表转换为我想要的类型)?
List<Country> countries = (List<Country>)(List<?>) getListOfAnyObject("countries",Country.type);
非常感谢!
【问题讨论】:
-
考虑将函数的名称更改为
getAll<Country>("country")... 根据您的需要,您也可以使用通用存储库模式,因此您只需说repo.GetAll();它知道什么你说的是