Generic function for calling back every kinds of methods with different arguments in C# -
i want have function able call function , retrieve proper value.
these examples of need:
var ilist<person> = invokefunction<ilist<person>>(repositoryperson.getallperson); var persion = invokefunction<person>(repositoryperson.getpersonbyid, 10); var int = invokefunction<int>(repositoryperson.runcustomstoreprocedure, 250,"text",521,10);
there no syntax allow since there no syntax allow call invokefunction method , pass in method call first parameter that.
specifically, type can declare invokefunction have first parameter kind of delegate type, need specify specific delegate type, gets square 1.
now, if modified syntax slightly, here's linqpad program demonstrates:
void main() { var t = new test(); invokefunction<int>(t, "add", 10, 20).dump(); invokefunction<int>(t, "negate", 10).dump(); invokefunction<int>(t, "semirandom").dump(); } public class test { public int add(int a, int b) { return + b; } public int negate(int value) { return -value; } public int semirandom() { return new random().next(); } } public static t invokefunction<t>(object instance, string methodname, params object[] arguments) { var method = instance.gettype().getmethod(methodname, arguments.select(a => a.gettype()).toarray()); return (t)method.invoke(instance, arguments); }
this example missing:
- error checking (null references)
- null parameter handling (if method has overloads, 1 pick?)
Comments
Post a Comment