Why do I get this error 'binding to target method' using Delegate.CreateDelegate?

£可爱£侵袭症+ 提交于 2019-12-24 02:47:10

问题


The Run2 method is run. But the Run method is not run. What is the reason ? The only difference between two methods is because parameter.

public class MyClass
{
    public string Name { get; set; }
}

[TestFixture]
public class Test
{
    public IEnumerable<T> TestMethod<T>(int i)
    {
        //do something
        return null;
    }

    public IEnumerable<T> TestMethod2<T>()
    {
        //do something
        return null;
    }

    [Test]
    public void Run()
    {
        MethodInfo mi = this.GetType().GetMethod("TestMethod").MakeGenericMethod(typeof(MyClass));
        var del = Delegate.CreateDelegate(typeof(Func<IEnumerable<MyClass>>), this, mi);
        var list = (IEnumerable<MyClass>)del.DynamicInvoke(0);
    }

    [Test]
    public void Run2()
    {
        MethodInfo mi = this.GetType().GetMethod("TestMethod2").MakeGenericMethod(typeof(MyClass));
        var del = Delegate.CreateDelegate(typeof(Func<IEnumerable<MyClass>>), this, mi);
        var list = (IEnumerable<MyClass>)del.DynamicInvoke();
    }
}

回答1:


The problem is here:

var del = Delegate.CreateDelegate(typeof(Func<IEnumerable<MyClass>>), this, mi);

You've said to bind your method to a Func<IEnumerable<MyClass>> delegate, but the actual method should be Func<int, IEnumerable<MyClass>> (because of the int argument to TestMethod). The following should correct it:

var del = Delegate.CreateDelegate(typeof(Func<int, IEnumerable<MyClass>>), this, mi);


来源:https://stackoverflow.com/questions/12939108/why-do-i-get-this-error-binding-to-target-method-using-delegate-createdelegate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!