c# - Two namespaces have identical classes, how can I prevent having to write two identical functions? -
i have been provided 2 libraries, each own namespaces, have identical class structures request part of api, different responses.
i want write function can handle both requests irrelevant of namespace type (i have experimented generics failed create solution).
here illustration of trying do:
public void function1() { namespace1.mytype type1 = new namespace1.mytype1(); type1.innertype = new namespace1.mytype2(); type1.performmethod1(); } public void function2() { namespace2.mytype type1 = new namespace2.mytype1(); type1.innertype = new namespace2.mytype2(); type1.performmethod1(); }
i have tried utilize generics @ method level in next way:
public void function1<ttype1, ttype2>() ttype1: namesspace1.type1, namesspace2.type1, new() ttype2: namespace1.type2. namespace2.type2(), new() { ttype1 type1 = new ttype1(); type1.innertype = new ttype2(); type1.performmethod1(); }
however, .net not allow level of constraints on generics. suggestions on how create generic function great.
thanks
generics in .net don't work way.
i think best way create mutual interface , somehow fit in library classes. question how that.
if type in question not sealed , creating instances yourself, can create derived class implements interface, automatically implemented inherited methods:
interface imytype { object innertype { get; set; } void performmethod1(); } class namespace1mytypewithinterface : namespace1.mytype, imytype {}
this assumes both types identical. if, example, type of innertype
different in each, situation gets more complicated. 1 way solve create interface generic in type of property.
if previous solution won't work you, can create adapter class each namespace. both adapters 1 time again share same interface , delegate each phone call instance of actual type.
class namespace1mytypeadapter : imytype { private readonly namespace1.mytype m_adapted; public namespace1mytypeadapter(namespace1.mytype adapted) { m_adapted = adapted; } public object innertype { { homecoming m_adapted.innertype; } set { m_adapted.innertype = value; } } public void performmethod1() { m_adapted.performmethod1(); } }
it's lot of repeated code, write 1 time , can utilize both classes same way.
yet alternative utilize dynamic
or reflection.
c# generics namespaces
No comments:
Post a Comment