c# - Generic type whose type parameter is an abstract base class -
let's have base class named animal
, 2 derived classes named lion
, tiger
. , i'd have generic type named animallist<animal>
contain members of animal
. example:
var list = new animallist<animal>(); list.add(new lion()); list.add(new tiger());
very straightforward far there's catch...i'd base class animal
abstract
. is, i don't want allow instance of base class created. however, making base class abstract not surprisingly results in error cs0310 (see complete example below).
i did come solution: make base class non-abstract required , throw exception default (parameterless) constructor:
public animal() { throw new system.notimplementedexception(); }
but makes me feel little uneasy. is there better way?
here's complete example illustrates scenario describe above:
// public class animal {} // ok public abstract class animal {} // 'abstract' keyword causes error 'cs0310' public class lion : animal {} public class tiger : animal {} public class animallist<t> : animal t : animal, new() { public void add(t animal) {} } class animallistdemo { static public void main(string[] args) { // following statement causes: // error cs0310 - 'animal' must non-abstract type // public parameterless constructor in order use // parameter 't' in generic type or method 'animallist<t>' var list = new animallist<animal>(); list.add(new lion()); list.add(new tiger()); } }
just remove new()
constraint. requires provide class can instantiated through new()
(which requirement about), abstract class can't this.
from msdn:
the new constraint specifies type argument in generic class declaration must have public parameterless constructor. to use new constraint, type cannot abstract.
Comments
Post a Comment