c# - Any better way to determine the type based on T and subclass -
writing bit of code deals response , request. both can in form of xml, , both can in form of c# object created through transform , serialization. (this .net 2.0)
response , request base implementations of larger message types. right have geteligibility , findcandidates.
example of model.messagemodel classes used below:
public partial class geteligibilityresponsemessage : responsemessage public partial class responsemessage : message because won't want duplicate mapping functionality i've decided use generics simplify process, , it's working out great:
base class code
public virtual model.messagemodel.message maptomodel<t>(xmldocument xml) { v3mapper mapper = new v3mapper(); model.messagemodel.message message = mapper.maptodomainmodel<t>(xml, environment) model.messagemodel.message; return message; } public virtual xmldocument maptoxml<t>(model.messagemodel.message message) { v3mapper mapper = new v3mapper(); xmldocument xml= mapper.maptov3message<t>(message, environment); return xml; } when code first called, has xml document. know document mapped request, , call virtual method overriden (and think it's ugly). reason keep mapping code in base not duplicate code, yet find doing exact thing want avoid following:
geteligibility : baseclass
public override model.messagemodel.message maptomodel<t>(xmldocument xml) { if(typeof(t).isassignablefrom(typeof(geteligibilityresponsemessage))) { return base.maptomodel<geteligibilityresponsemessage>(xml); } else if (typeof(t).isassignablefrom(typeof(geteligibilityrequestmessage))) { return base.maptomodel<geteligibilityrequestmessage>(xml); } return null;//because quick code snippet } is there more elegant way of doing this? know if i'm working response or request. want leave functionality open it's not tightly-coupled, @ same time have functional , fast.
this implemented number of different message types, , hate copy/paste style of coding, elegant solution great, i'm not sure if there one. (.net 2.0)
you can use methodinfo.makegenericmethod method avoid having check types before calling generic method. below quick usage example:
class program { public static void generic<t>(t todisplay) { console.writeline("\r\nhere is: {0}", todisplay); } static void main(string[] args) { methodinfo mi = typeof(program).getmethod("generic"); methodinfo miconstructed = mi.makegenericmethod(typeof(datetime)); datetime = datetime.now; miconstructed.invoke(null, new object[] { }); } } notice used typeof(datetime), in case can replace typeof(t) achieve desired loosely-coupled solution.
Comments
Post a Comment