c# - Can params be used to call methods with strongly typed parameters? -


i have method calls delegate based on state of network. method must decide call method( server, client ). in order work method, i've defined following delegate:

public delegate void networkcall( params object[] args ); 

this take parameter, work methods exact same signature. results in stuff:

protected virtual void donetowrkmove( params object[] args ) {     destination = ( vector3 )args[0]; } 

which not ideal solution. possible "unpack" objects in 'args' more typesafe method call? example:

protected virtual void donetowrkmove( vector3 newdestination ) {     destination = newdestination; } 

i'm not sure grasp use-case here. seems more flexible solution involve true serialization/deserialization data being sent, allow type-safe communications end-to-end.

that said, while delegates don't allow you're trying directly, can create generic method automate of work:

delegate void callback(params object[] args);  static void method1(params string[] args) { }  static callback wrap<t>(action<t[]> action) {     return (callback)((object[] args) => action(args.cast<t>().toarray())); }  static void main(string[] args) {     callback callback1 = wrap<string>(method1); } 

this cast each element of args array type specified. of course, requires wrapped method has array sole parameter, e.g. params array. handle more specific example, this:

static void method2(string arg) { }  static callback wrap<t>(action<t> action) {     return (callback)((object[] args) => action((t)args[0])); }  static void main(string[] args) {     callback callback2 = wrap<string>(method2); } 

as .net generic delegate types action , func, have declare specific wrapper method each parameter-count delegate. above work 1 parameter. if have examples of 2 parameters, you'd need add:

static void method3(string arg1, bool arg2) { }  static callback wrap<t1, t2>(action<t1, t2> action) {     return (callback)((object[] args) => action((t1)args[0], (t2)args[1])); }  static void main(string[] args) {     callback callback3 = wrap<string, bool>(method3); } 

and on. whether it's worth write these little wrappers of course depend on how you'd use them. i'd after third or fourth callback, you'd find worthwhile.

of course, i'm still thinking might better off serialization-based approach instead. that's different question. :)


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -