Passing around member functions in C# -


mostly comes handy c# delegates store object member function. there way, store -- , pass parameters -- member function itself, old pointer-to-member-function in c++?

in case description less clear, give self-contained example. and, yes, in example insistence pass around member functions totally pointless, have more serious uses this.

class foo {     public int { get; set; }     /* can done?     public static int apply (foo obj, ???? method, int j) {         return obj.method (j);     }     */     public static int applyhack (foo obj, func<int, int> method, int j) {         return (int) method.method.invoke (obj, new object [] { j });     }     public static readonly foo _ = new foo (); // dummy object applyhack      public int multiply (int j) {         return * j;     }     public int add (int j) {         return + j;     } } class program {     static void main (string [] args) {         var foo = new foo { = 7 };         console.write ("{0}\n", foo.applyhack (foo, foo._.multiply, 5));         console.write ("{0}\n", foo.applyhack (foo, foo._.add, 5));         console.readkey ();     } } 

you see, workaround i've found rather ugly , slow.

taking existing code:

public static int applyhack (foo obj, func<int, int> method, int j) {     return (int) method.method.invoke (obj, new object [] { j }); } 

you this:

public static int applyhack (foo obj, func<int, int> method, int j) {     var func = (func<int,int>)delegate.createdelegate(typeof(func<int,int>), obj, method.method);      return func(j); } 

this create new delegate around method , new object. take first example:

public static int apply (foo obj, ???? method, int j) {     return obj.method (j); } 

the type looking system.reflection.methodinfo , this:

public static int apply (foo obj, methodinfo method, int j) {     var func = (func<int,int>)delegate.createdelegate(typeof(func<int,int>), obj, method);      return func(i); } 

note while allocating delegates each invocation, believe still faster using reflection, since not have box function input/output, nor store in object[] arrays.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -