c# - Combining generic methods and overloads -


i have following method:

public void set<t>(ienumerable<t> records) {      foreach (var record in records)      {         set(record);      }  } 

i either 1 of following set methods called, depending on t:

    public void set(recordtype1 record)     {         // recordtype1 logic     }      public void set(recordtype2 record)     {         // logic applicable recordtype2     } 

hopefully, can see i'm attempting allow set method called inferred @ runtime. "isn't working" (i.e. won't compile it's expecting recordtype1).

question

how can keep kind of structure without testing type before sending records off set method?

why don't create interface (irecordtype), allow recordtype1 , recordtype2 inherit it, move main logic of each set method interface.

public interface irecordtype {     void set(...); } public void set(ienumerable<irecordtype> records) {     foreach (var record in records)     {         record.set(...);     } } 

this more maintainable solution. , allows better polymorphism.

edit: resource at: https://msdn.microsoft.com/en-us/library/3b5b8ezk%28v=vs.90%29.aspx

also, little sidebar: interfaces can not share methods, properties , events, well. if recordtype1 , recordtype2 share several common properties, can add properties interface, , use irecordtype wherever have needed distinguish between 2 use of these properties, methods or events. likewise, code inside of properties, methods or events is permitted rely on other properties, methods, events or fields specific object itself. purpose of object-oriented languages (c#) , polymorphism.

edit: result of discussion in comments, wanted add more information decision between using oop approach (interface, abstract class, class) , dynamic approach striplingwarrior suggested:

if don't have access actual implementation details of recordtype1 or recordtype2, or unable alter design of application (due impeding reliance on set(recordtype1) , set(recordtype2) methods, may find more fruitful take approach of using dynamic. there other options out there may not have thought of - give 1 of them go. downside dynamic approach requires .net 4.0.

also, more considerations: if have access recordtype1 , recordtype2 implementation details, cannot change set(recordtype1) , set(recordtype2) far definition, modify body of them:

public void set(recordtype1 record) {     record.set(...); }  public void set(recordtype2 record) {     record.set(...); } 

this preserves entire application structure, while decreasing code maintenance , allowing polymorphism.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -