Peter Morris
Peter Morris

Reputation: 23224

Delegate.CreateDelegate - method arguments are incompatible

Given aMethodInfo for the following method

public class MyEffects
{
  public Task Test(object action, IDispatcher dispatcher)
  {
    return Task.CompletedTask;
  }
}

Why does the following CreateDelegate code throw System.ArgumentException: method arguments are incompatible?

Delegate.CreateDelegate(
    type: typeof(Func<object, IDispatcher, Task>),
    method: discoveredEffect.MethodInfo);

As does this

Delegate.CreateDelegate(
    type: typeof(Func<object, object, IDispatcher, Task>),
    method: discoveredEffect.MethodInfo);

Upvotes: 2

Views: 1831

Answers (1)

thehennyy
thehennyy

Reputation: 4218

Since you want to create to delegate to a non static method you have to provide a target using the CreateDelegate(Type, Object, MethodInfo) overload:

using System;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        var method = typeof(MyEffects).GetMethod("Test");
        var obj = new MyEffects();
        var del = Delegate.CreateDelegate(typeof(Func<object, IDispatcher, Task>), obj, method);
        Console.WriteLine(del);
    }
}

public class MyEffects
{
  public Task Test(object action, IDispatcher dispatcher)
  {
    return Task.CompletedTask;
  }
}

public interface IDispatcher {} 

returns

System.Func`3[System.Object,IDispatcher,System.Threading.Tasks.Task]

Upvotes: 3

Related Questions