c# - Complex inheritance situation. Returning base object from derived class -


i have complex situation involving inheritance. have base dataobject class invoice class inherits from. want save invoice object using dataobject save method , return invoice object saved.

public abstract class dataobject {     public virtual dataobject save() {         // save data         return this;     } } 

derived classes

public class invoiceobject : dataobject {     // base data class goes here }  public class invoice : invoiceobject {     public override dataobject save() {           // somehow return invoice object here           return base.save();     } } 

i want avoid using casts if possible. insight helpful. arguments sake structure must remain same. cannot remove invoiceobject object , save method must return entire invoice object saved database. not sure if possible, hope is.

working within constraints, seems easiest way declare save abstract (as invoiceobject), , letting concrete templatized subclasses override it, so:

public abstract class dataobject<t> {      public abstract t save(); }  public abstract class invoiceobject<t> : dataobject<t> {     // base data class goes here     }  public class invoice : invoiceobject<invoice> {     public override invoice save() {                     return this;     } } 

edit: in response comment, having default "save" implementation means whatever object save returns must dataobject<t>, since default implementation of save return this; inside of dataobject<t> (hope makes sense).

you can using curiously recurring template pattern, doing requires return dataobject<t> save, so:

public abstract class dataobject<t> t : dataobject<t>{      public virtual dataobject<t> save(){         return this;      } }  public abstract class invoiceobject<t> : dataobject<t> t : dataobject<t> {     // base data class goes here     }  public class invoice : invoiceobject<invoice> {  } 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -