c# - Casting an IEnumerable to IEnumerable<T> with reflection -
so, need phone call 3rd party method, has signature this
thirdpartymethod<t>(ienumerable<t> items)
my problem don't know type of object @ compile time.
at compile time have this
ienumerable myobject; type typeofenumerableihave;
sooo..can reflection help me out here somehow?
for simplicity sake, pretend have method this
void dowork(ienumerable items, type type) { //in here have phone call thirdpartymethod<t>(ienumerable<t> items); }
since have ienumerable myobject;
, signature thirdpartymethod<t>(ienumerable<t> items)
able utilize cast()
:
thirdpartymethod(myobject.cast<t>())
if don't know t
type @ compile time should provide @ runtime.
consider third-party library looks this
public static class external { public static void thirdpartymethod<t>(ienumerable<t> items) { console.writeline(typeof(t).name); } }
if have following
type thetype = typeof(int); ienumerable myobject = new object[0];
you can generic methods thirdpartymethod
, cast
@ runtime
var targetmethod = typeof(external).getmethod("thirdpartymethod", bindingflags.static | bindingflags.public); var targetgenericmethod = targetmethod.makegenericmethod(new type[] { thetype }); var castmethod = typeof(enumerable).getmethod("cast", bindingflags.static | bindingflags.public); var caxtgenericmethod = castmethod.makegenericmethod(new type[] { thetype });
finally phone call method:
targetgenericmethod.invoke(null, new object[] { caxtgenericmethod.invoke(null, new object[] { myobject }) });
c# reflection ienumerable
No comments:
Post a Comment