c# - How to return generic object that could be from two different types -
i’m trying create middle layer allow me connect either live service or test service without making changes client.
i need return generic object called product
use in client. middle layer don't need know how or it's from. middle layer connects live , test service , call method stuff need.
the problem returning product got whichever service client. method expecting product
it's trying send liveservice.product
or testservice.product
.
is there way convert these types generic product
type can returned client?
below have created far.
client
connection conn = new connection("test"); iserviceimplementation service = conn.getserviceimplementation(); product prod = service.getproductusingid(123);
middle layer
public interface iserviceimplementation { product getproductusingid (int productid); } public class connection { private string mode; public connection(string _mode) { mode = _mode; } public iserviceimplementation getserviceimplementation() { if (mode == "live") { return new liveservice(); } else if (mode == "test") { return new testservice(); } else { return null; } } } public class liveservice : iserviceimplementation { public product getproductusingid (int productid) { liveservice.service live = new liveservice.service(); return live.getproduct(2638975); } } public class testservice : iserviceimplementation { public product getproductusingid (int productid) { testservice.service test = new testservice.service(); return test.getproduct(2638975); } }
the easiest answer define own product
class return.
public class myproduct { //some properties } public myproduct getproductusingid (int productid) { liveservice.service live = new liveservice.service(); var product = live.getproduct(2638975); var myproduct = new myproduct(); //copy properties myproduct.someprop = product.someprop; //etc return myproduct; }
the alternative use partial classes. product
class in each service namespace should defined partial
. create part of partial in file each service type , inherit interface:
namespace somesharednamespace { public interface iproduct { //shared properties need } } namespace liveservice { public partial class product : iproduct { //implement interface } } namespace testservice { public partial class product : iproduct { //implement interface } }
now each product
implements iproduct
interface, return that
public iproduct getproductusingid (int productid) { liveservice.service live = new liveservice.service(); return live.getproduct(2638975); }
Comments
Post a Comment