c# - Wrapper method which takes interface argument and operates on sub-class -
i have interface "i" contains field "id". interface, have objects a, b, c, d implement it. in separate class database, have 4 methods named foo operate on a, b, c, , d.
while writing method foo operates on bunch of dictionary objects containing caches of subclasses, noticed writing same bit of code on , on again. looks like
foreach(a in acache.values) { int id = a.id; database.foo(a); int newid = a.id; bar(a); } i have caches, there's 11 total, attempting write sort of generic method can perform these operations. bar operates on i, there no issues that. problem i'm seeing database.foo, because though there implementations of foo types implement i, writing simple wrapper such:
void foowrapper<t>(t obj) t: { database.foo(obj); } does not fit bill. how can work? prefer avoid using reflection if possible.
edit: requested, signature(s) of database.foo:
public bool foo(ref aitem); //returns true based on success of query public bool foo(ref b bitem); public bool foo(ref c citem); edit2: alright, able write foowrapper such:
foowrapper<t>(ienumerable<t> items, func<t, bool> foodelegate) t : { foreach(t item in items) { int oldid = item.id; foodelegate(item); int newid = item.id; bar(item); } } and call such:
foowrapper(acache.values, (func<a, bool>) database.foo); this works, i'd prefer more elegant, there other things avoid passing in delegate?
if you're using dependency injection, trivial register components implementing interface idatabasedoingstuffto method taking classes account.
interface idatabasedoingstuffto<t>{ void dostuff(database db, t t); } then in code have
foreach(a in acache.values) { process(db, a); } public void process(database db, i) { int id = i.id; // retrieve idatabasedoingstuffto var iddsti = retrievedatabasebridge(i); iddsti.dostuff(db, i); int newid = i.id; bar(i); } the retrievedatabasebridge come from:
- dependency injection
- a key value map between typeof , instance of bridging class (a simple dictionary)
- configuration (mapping between types in config file...)
so there solutions, may need more information regarding have available
Comments
Post a Comment