consider generic method follow:
class someclass { public static void somemethod<t>(func<t>); } i call method using reflection. how far make it:
_somemethod = typeof(someclass).getmethod("somemethod", bindingflags.public | bindingflags.static); type type = typeof(sometype); //actually sometype extracted using reflection , it's not fixed methodinfo tobecalled = _somemethod.makegenericmethod(type); object obj = activator.createinstance(type); tobecalled.invoke(null, () => obj); but gives compile error:
error cs1660: cannot convert `lambda expression' non-delegate type `object' (cs1660) which absolutely acceptable what's work around?
please keep in mind closure created using lambda need, don't eliminate it.
[update]
to clarify situation makes sense; functor created using lambda instantiator used somemethod create instance of class sometype. don't want create object in functor, instead return collection of instantiated objects before. easiest way having obj in closure returned lambda, don't think?
i think looking pass known object ot generic method takes func<t> , "func" identity. 1 more wrapper may help:
public void somemethodinvokerruntime(type typeofsomeclass, object obj) { var _somemethod = this.gettype().getmethod("somemethodinvoker", bindingflags.public | bindingflags.static); methodinfo tobecalled = _somemethod.makegenericmethod(obj.gettype()); tobecalled.invoke(null, new[]{typeofsomeclass, obj}); } public static void somemethodinvoker<t>(type typeofsomeclass, t obj) { var _somemethod = typeofsomeclass.getmethod("somemethod", bindingflags.public | bindingflags.static); methodinfo tobecalled = _somemethod.makegenericmethod(typeof(t)); func<t> = () => obj; // main part - typed delegate tobecalled.invoke(null, new[]{that}); } sample usage:
static class test { public static void somemethod<t>(func<t> f) { console.writeline((t)(f())); } } somemethodinvoker(typeof(test), 3); object obj = "test"; somemethodinvokerruntime(typeof(test), obj); alternatively can build expression , compile function shown in jon skeet's answer.
Comments
Post a Comment