c# - generic type of class property -


i have following classes:

basefield:

public abstract class basefield {     ...     public basefield()     {      }      public basefield(e_fieldtype fieldtype)     {         _fieldtype = fieldtype;     } } 

textfield:

public class textfield : basefield {     ...     public textfield() : base(e_fieldtype.text)     {      } } 

datefield:

public class datefield : basefield {     ...     public datefield() : base(e_fieldtype.date)     {      } } 

and datablock class should contain textfield or datefield:

public class datablock<t> : baseblock t : basefield, new() {     ...     private t _field;     public datablock(string name): base(name, e_blocktype.data)      {         _field = new t();                 } } 

the following line works fine:

datablock<textfield> db = new datablock<textfield>("qwe"); 

but not possible write code:

public observablecollection<datablock<basefield>> datablocklist { get; set; }  public datablockviewmodel() {     datablocklist = new observablecollection<datablock<basefield>>();     datablocklist.add(new datablock<textfield>("qwe"));     datablocklist.add(new datablock<datefield>("asd")); } 

the error is:

'basefield' must non-abstract type public parameterless constructor in order use parameter 't' in generic type or method 'datablock<t>'

could please advise how solve issue can create observablecollection<datablock<basefield>> collection?

i can remove new() public class datablock<t> : baseblock t : basefield and

public datablock(string name): base(name, e_blocktype.data)  {     //_field = new t();             } 

in case can create datablocklist = new observablecollection<datablock<basefield>>();

but not possible write:

datablocklist.add(new datablock<textfield>("qwe")); datablocklist.add(new datablock<datefield>("asd")); 

there 2 ways rid of error:

1) can make class basefield non-abstract

public abstract class basefield {     ...     public basefield()     {      }      public basefield(e_fieldtype fieldtype)     {         _fieldtype = fieldtype;     } } 

2) pass new basefield object constructor parameter datablock , remove new() constraint.

public class datablock<t> : baseblock t : basefield {     ...     private t _field;     public datablock(string name, t field): base(name, e_blocktype.data)      {         _field = field;                 } } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -