为什么使用Delegate.CreateDelegate得到这个错误'绑定到目标方法'? [英] Why do I get this error 'binding to target method' using Delegate.CreateDelegate?

查看:90
本文介绍了为什么使用Delegate.CreateDelegate得到这个错误'绑定到目标方法'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行Run2方法。但是Run方法没有运行。是什么原因 ?
两种方法之间的唯一区别是因为参数。

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

[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();
}
}


解决方案

问题在这里:

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

你已经说过要将你的方法绑定到一个 Func< IEnumerable&MyClass> ;> 委托,但实际的方法应该是 Func< int,IEnumerable< MyClass>> (因为 int 参数 TestMethod )。以下内容应该更正:

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


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();
    }
}

解决方案

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);

这篇关于为什么使用Delegate.CreateDelegate得到这个错误'绑定到目标方法'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆