c# - Can we make this method generic? -
i saw method in sample xamarin, using json accessing rest server:
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> (); } }); }
where "createrequest" , "readresponsetext" methods interact rest server, receiving list of countries deserialize , return in list. now, i'm trying make method generic in order receive type , return generic list of objects of specified type, this:
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 generic list based on specified type objects = newtonsoft.json.jsonconvert.deserializeobject<list<object>> (response); // not sure how handle line return objects; } catch (exception ex) { console.writeline (ex); return ex.message; } }); }
so question is, how can create method above in order use more , less (casting list desired type)?
list<country> countries = (list<country>)(list<?>) getlistofanyobject("countries",country.type);
many in advance!
try this..
public static task<list<t>> getlistofanyobject<t>(string requested_object) { return task.factory.startnew (() => { try { var request = createrequest (requested_object); string response = readresponsetext (request); return newtonsoft.json.jsonconvert.deserializeobject<list<t>> (response); // not sure how handle line } catch (exception ex) { console.writeline (ex); return ex.message; } }); }
called so..
list<country> countries = getlistofanyobject<country>("countries");
Comments
Post a Comment