c# - Declaring an array of base class and instantiating inherited members -


i have class defined generic:

public class genericdatastore<t> {      // underlyingdatastore class manages queue, or linked list      private underlyingdatastore<t> dataqueue = new underlyingdatastore<t>();      public void adddata(t data) { dataqueue.add(data); }      public t getlastdata() { dataqueue.getlastdata(); } } 

i have different derived classes based on class:

public class bytedatastore : genericdatastore<byte> { } public class doubledatastore : genericdatastore<double> { } public class pobjdatastore : genericdatastore<pobj> // pobj class declared somewhere { } 

then, have "manager" class looks like:

public class datamanager {      /* here, want declare 2 dim array [,] holds pointers         data stores. depending on other variables, array may need         point doubledatastore, bytedatastore, etc. following doesn't work,         since genericdatastore must declared generic type: */          genericdatastore [,] manageddatastores; // can not compile          public datamanager() {            (int i=0; i<numstores; i++) {                (int j=0; j<numcopies; j++) {                    // objtype utility function have returns type                    if (objtype(i,j) == typeof(byte)) {                          manageddatastores[i,j] = new bytedatastore();                    } else if (objtype(i,j) == typeof(double)) {                          manageddatastores[i,j] = new doubledatastore();                    }                }            }         }          void add(int id, int copyid, byte data) {              manageddatastores[i,j].add(data);         }  } 

there might other, better ways this. essentially, want have different data stores different object types, can managed class. want 'manager' class exposed user (like api), , no direct access underlying classes.

thanks in advance.

i'm afraid 1 of instances generic's don't 1 bit. definition, must know generic type @ compile time, rather runtime. runtime type-indiference, need old-fashioned way.

public class datastore {      // underlyingdatastore class manages queue, or linked list      private underlyingdatastore dataqueue = new underlyingdatastore();      public void adddata(object data) { dataqueue.add(data); }      public object getlastdata() { dataqueue.getlastdata(); } } 

this, has obvious drawback of boxing/unboxing- need calling-code know type's should dealing in order cast.

however, use the other answer, long you're able cast manageddatastore correct generic type.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -