c# - Issues with the "where" in generic inheritance -
in following code problem on line entities = dospecialstuff(entities);
because i'm "missing" in part dospecialstuff()
methode
error
the type 't' cannot used type parameter 't' in generic type or method
'myworkclass<t>.dospecialstuff<t>(ienumerable<t> entities)'. there no implicit reference conversion 't' 'ispezial'.)
code
here ineritance structure
public class baseclass { } public interface ispezial { int myspecial{get;set;} } public class class1 : baseclass { } public class class2 : baseclass, ispezial { public int myspecial{ get;set;} }
here data provider
public class myrepository { public static ienumerable<tresult> load<tresult>() tresult : baseclass, new() { list<tresult> myenum = new list<tresult>(); if (typeof(ispezial).isassignablefrom(typeof(tresult))) { myenum.add((new class2() { myspecial = 0 }) tresult); myenum.add((new class2() { myspecial = 1 }) tresult); myenum.add((new class2() { myspecial = 2 }) tresult); } else { myenum.add((new class1() tresult)); myenum.add((new class1() tresult)); myenum.add((new class1() tresult)); } return myenum; } }
and there class stuff , provides errors boss
public class myworkclass<t> t : baseclass, new() { public void donormalstuff() { var entities = myrepository.load<t>(); if (typeof(ispezial).isassignablefrom(typeof(t))) { entities = dospecialstuff(entities); } } public ienumerable<t> dospecialstuff<t>(ienumerable<t> entities) t : ispezial { var list = new list<t>(); return list.where(special => special.myspecial==2); } }
some further question
how can avoid new()
in where's?
and how can change add part myrepository
myenum.add(new class1());
instead of myenum.add((new class1() tresult));
without changing return ienumerable<tresult>
?
since there no implicit conversion between t (baseclass or child of baseclass), it's not enough check if ispezial assignable (which do, , it's that), need explicitly cast variable when passing parameter, , cast back. it's not best class design, though.
entities = dospecialstuff(entities.cast<ispezial>()).cast<t>();
2nd question: since explicitly call class2() , class1() constructors, you're not relying on polymorphism/generic typing of c#, why new() constraint there (if wrote new t(), example). long keep code that, can remove constraint.
3rd: can make use of dynamics keyword, make list of dynamic type, , cast in last moment:
list<dynamic> myenum = new list<dynamic>(); //your code myenum.add((new class2() { myspecial = 0 })); //it's ok write want //your code return myenum.cast<tresult>();
Comments
Post a Comment