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

后端 未结 3 1688
鱼传尺愫
鱼传尺愫 2020-12-03 23:44

I have a struct with a private method that I\'d like to invoke. Since I plan to do this in a performance critical section, I\'d like to cache a delegate to perform the actio

3条回答
  •  粉色の甜心
    2020-12-03 23:56

    Interesting problem. From this bug report, it looks like this might be a bug that will be fixed in a 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, I think this bug report is regarding a different issue, so the behavior you're seeing may not actually be a bug.

    From that bug report, I gleaned that there is a work-around if you specify the first argument of your delegate as being passed by reference. Below is a complete working example:

    public struct A
    {
        private int _Value;
    
        public int Value
        {
            get { return _Value; }
            set { _Value = value; }
        }
    
        private int SomeMethod()
        {
            return _Value;
        }
    }
    
    delegate int SomeMethodHandler(ref A 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);
    
            A instance = new A();
    
            instance.Value = 5;
    
            Console.WriteLine(d(ref instance));
        }
    }
    

    EDIT: Jon Skeet's answer here also discusses this issue.

提交回复
热议问题