c# - Generic property-list with any generic argument -


i need instantiate list-property generic type can anything.

so main-method looks this: (in real, parsingobject<t> objects service)

public static void main() {     parser parser = new parser();     parser.addanobject(         new parsingobject<int>{propertyname = "firstproperty", active=true, defaultvalue=1}     );     parser.addanobject(         new parsingobject<bool>{propertyname = "secondproperty", active=false, defaultvalue=false}     );     parser.parse(); } 

parsingobject gets type (i think string, bool, int,...) generic. in parser need add object list<parsingobject<t>> like:

public class parser {     private readonly list<parsingobject<t>> _listofobjects = new list<parsingobject<t>>();      public void addanobject<t>(parsingobject<t> item)     {         _listofobjects.add(item);     }      public void parse()     {         foreach(var item in _listofobjects.where(w=>active))         {             dosomething(item);         }     } } 

but know, cannot set t generic argument when instantiating list (compiler crying..). solve using arraylist - can't access properties of each object. (see parse()-method)

for completeness, here parsingobject<t>-class:

public class parsingobject<t> {     public string propertyname { get; set; }     public bool active { get; set; }     public t defaultvalue { get; set; } } 

any idea how solve this? cannot modify parsingobject<t>-class.

depending on end goal, maybe sufficient:

public class parsingobjectbase {     public string propertyname { get; set; }     public bool active { get; set; }     public type valuetype { get; protected set; }      public object defval { get; protected set; } } public class parsingobject<t> : parsingobjectbase {     public object defaultvalue     {         { return (t)defval; }         set { defval = value; }     }      public parsingobject()     {         valuetype = typeof(t);     } }  private readonly list<parsingobjectbase> _listofobjects = new list<parsingobjectbase>();  public void addanobject<t>(parsingobject<t> item) {     _listofobjects.add(item); }  public void parse() {     foreach(var item in _listofobjects.where(w=>w.active))     {         dosomething(item); //do exactly?     } } 

you can't without casting either concrete parsingobject<t> or defval value in case, have type information stored in 1 place , have access specific properties. maybe changing valuetype kind of enum easier use switch?


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -