How to create a delegate to an instance method with a null target?

前端 未结 3 1513
遇见更好的自我
遇见更好的自我 2020-12-15 12:06

I\'ve noticed that the Delegate class has a Target property, that (presumably) returns the instance the delegate method will execute on. I want to do something like this:

3条回答
  •  情话喂你
    2020-12-15 12:31

    It is possible with Delegate.CreateDelegate, exactly with the overload with the signature: CreateDelegate (Type, object, MethodInfo)

    If you specify "null" for the second parameter (target) then you have to put an extra parameter into the delegate type, that specifies the instance type, and when you invoke the delegate, the instance has to be passed as first argument, followed by the "real" parameters of the method.

    class Test
    {
        public int AddStrings(string a, string b)
        {
            return int.Parse(a) + int.Parse(b);
        }
    
        static void Main()
        {
            var test = new Test();
            var methodInfo = test.GetType().GetMethod("AddStrings");
            // note the first extra parameter of the Func, is the owner type
            var delegateType = typeof(Func);
            var del = Delegate.CreateDelegate(delegateType, null, methodInfo);
    
            var result = (int)del.DynamicInvoke(test, "39", "3");
        }
    }
    

提交回复
热议问题