Sunday 15 August 2010

c# - Passing a data class as a variable to a function -



c# - Passing a data class as a variable to a function -

i trying build reusable module api calls in c#. want utilize several different apis. having problem passing info classes dynamically variable function handles api calls.

so let's say, example, calling 2 different apis, we'll phone call them "api #1" , "api #2". , have next classes:

// format of response api #1 public class api01get { public int orderid { get; set; } public datetime orderdate { get; set; } } // format of response api #2 public class api02get { public bool isgreen { get; set; } public string name { get; set; } }

here phone call function. works fine if utilize 1 of info classes straight this:

var result = callapi<api02get>(baseaddress, requesturi);

but doesn't allow me flexibility after.

here definition of function (i have left out other parameters here not impact things):

private async task<tresult> callapi<tresult>(uri baseaddress, string requesturi) { using (var client = new httpclient()) { client.baseaddress = baseaddress; client.defaultrequestheaders.accept.clear(); client.defaultrequestheaders.accept.add(new mediatypewithqualityheadervalue("application/json")); httpresponsemessage response = new httpresponsemessage(); response = await client.getasync(requesturi); if (response.issuccessstatuscode) { tresult result = await response.content.readasasync<tresult>(); } } // other stuff... homecoming result; }

now hung up. must thinking in wrong way, trying example:

object apimodel; switch (whichapi) { case "api_01_get": apimodel = new api01get(); break; case "api_02_get": apimodel = new api02get(); break; // other cases... default: break; } var result = callapi<apimodel>(baseaddress, requesturi);

i error when attempting lastly line. "the type or namespace name 'apimodel' not found (are missing using directive or assembly reference?)". have tried other things, version seemed me closest posted.

so unsure how accomplish or maybe there improve way altogether. appreciate feedback , happy clarify if necessary. in advance.

unfortunately, cannot utilize generics here without reflection dynamically invoke callapi<t>.

luckily, httpcontentextensions has overloads allows pass in type. need overload method , create minor tweak readasasync.

private async task<object> callapi(uri baseaddress, string requesturi, type apitype) { using (var client = new httpclient()) { .... if (response.issuccessstatuscode) { object result = await response.content.readasasync(apitype); } } .... homecoming result; }

you may still need alter of code prior though since stuck object.

c#

No comments:

Post a Comment