c# - How to call a generic method using a type returned from a different method? -
i have 2 types person , organisation both inheriting icontact
.
i have method returns 1 of these types based on logic
private type getpersonororganisation(string variable) { either returns person or organisation type }
i have method queries database persons or orgs:
public static iqueryable<t> query<t>(this iuow uow) t : icontact { return uow.query<t>(); }
my question how can use type returned getpersonororganisation
call query.
so say:
var contacttype = getpersonororganisation(string variable); var contact = query<contacttype>();
where contacttype either person or organisation.
well won't compile , that's question. how make query on right type database based on returned getpersonororganisation
.
moving between type
, generics major pain; answer without refactoring is: reflection; like:
var method = typeof(sometype).getmethod("query").makegenericmethod(contacttype); // getch query<t>(this iuow) method var contact = (icontact)method.invoke(null, new object[] { uow });
which pretty horrible. if possible, suggest rewriting query<t>
method query(type type)
method (returning icontact
), still trivially allows generic query<t>
helper method existing code, via return (t) query(typeof(t));
. reverse not case, however.
if passing instance of type t
into method, there tricks can simplfiy this, using dynamic
perform type/generics/method resolution you.
Comments
Post a Comment