c# - IComparer<T> child as a generic param could not be used in Sort -
got stuck trying sort list<>
in c#.
i have interface type implementation class:
public interface iroom { // ... } public class room : iroom { // ... }
and base of operations class comparers:
public abstract class roomcomparer : icomparer<iroom> { public roomcomparer() { } public abstract int compare(iroom x, iroom y); }
and 2 children:
public class standardmultipliedsquaremeterscomparer : roomcomparer { public standardmultipliedsquaremeterscomparer() { } public override int compare(iroom a, iroom b) { // ... } } public class squaremeterscomparer : roomcomparer { public squaremeterscomparer() { } public override int compare(iroom a, iroom b) { // ... } }
now, here's problems begin: got generic class hotel
list of room
instances:
public class hotel<troom, tcomparer> : ihotel, ienumerable<troom> troom : iroom tcomparer : roomcomparer, new() { public list<troom> rooms; protected tcomparer comparer; public hotel(troom[] rooms) { rooms = new list<troom>(); rooms.addrange(rooms); comparer = new tcomparer(); rooms.sort(comparer); } }
and here's problem - got 2 errors on line rooms.sort(comparer);
:
error cs1502: best overloaded method match `system.collections.generic.list.sort(system.collections.generic.icomparer)' has invalid arguments (cs1502)
error cs1503: argument #1' cannot convert
tcomparer' look type `system.collections.generic.icomparer' (cs1503)
i tried many different solutions, no result. what's happening?
note: using mono 3.10.0
on ubuntu
you're trying utilize generic contravariance (if comparer can compare 2 troom
values, should able compare 2 iroom
values), usually fine - when troom
known class type. can prepare requiring troom
reference type:
where troom : class, iroom
at point, contravariance works fine, , well. require room types genuinely classes, of course.
do need hotel generic this? seems little much overkill me...
c# sorting generics mono
No comments:
Post a Comment