Featured post
c# - How can I make this generic method more flexible? -
i'm working library (treeview in gtk specific) allows sort passing function compares 2 rows. simplified version of function signature might this:
int somesortfunc (foo foo1, foo foo2) { // return -1 if foo1 < foo2, 0 if foo1 == foo2, 1 if foo1 > foo2 }
i can't implement foo.compareto (foo)
, because want sort differently depending on context. there several fields in foo
sort by. sort priority of each field depends on context. write this:
int sortfunc<t> (foo foo1, foo foo2, params func<foo, t> [] selectors) t : icomparable<t> { return selectors .select (s => s (foo1).compareto (s (foo2))) .firstordefault (i => != 0); } // compare somestring, someint, somebar int somesortfunc (foo foo1, foo foo2) { // won't compile, because string, int, , bar different types. return sortfunc (foo1, foo2, f => f.somestring, f => f.someint, f => f.somebar); }
this won't compile, because t
in func<foo, t>
different string
, int
, , bar : icomparable<bar>
(in other words, there no way resolve t
in sortfunc<t>
).
is there way write function such each selector can return different type, long each type sometype
implements icomparable<sometype>
?
i simplify , accept function returning non-generic icomparable
. can pass in functions returning primitives without needing figure out number of generic type parameters function need, truthfully need type parameters each of functions provided.
int sortfunc(foo foo1, foo foo2, params func<foo, icomparable>[] selectors)
- Get link
- X
- Other Apps
Comments
Post a Comment