c# - How can I create an open Delegate from a struct's instance method? -


i have struct private method i'd invoke. since plan in performance critical section, i'd cache delegate perform action. problem can't seem bind method delegate.createdelegate. struct in question not creation , used in interaction third party library. struct in question looks this::

public struct {      private int somemethod()      {         //body go here      } } 

and following code fail "error binding target method".

delegate.createdelegate(typeof(func<a,int>),typeof(a).getmethod("somemethod",bindingflags.instance | bindingflags.nonpublic)); 

i know can write expression tree perform action, seems odd can't use normal goto these things delegate.createdelegate method.

the above code works fine if a class. issue arises because a struct. msdn documentation incorrect overload of createdelegate work on non-static methods.

interesting problem. bug report, looks might bug fixed in future version of .net: http://connect.microsoft.com/visualstudio/feedback/details/574959/cannot-create-open-instance-delegate-for-value-types-methods-which-implement-an-interface#details

edit: actually, think bug report regarding different issue, behavior you're seeing may not bug.

from bug report, gleaned there work-around if specify first argument of delegate being passed reference. below complete working example:

public struct {     private int _value;      public int value     {         { return _value; }         set { _value = value; }     }      private int somemethod()     {         return _value;     } }  delegate int somemethodhandler(ref instance);  class program {     static void main(string[] args)     {         var method = typeof(a).getmethod("somemethod", bindingflags.instance | bindingflags.nonpublic);          somemethodhandler d = (somemethodhandler)delegate.createdelegate(typeof(somemethodhandler), method);          instance = new a();          instance.value = 5;          console.writeline(d(ref instance));     } } 

edit: jon skeet's answer here discusses issue.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -