2

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

1 回答 1

3

问题在这里:

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

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

var del = Delegate.CreateDelegate(typeof(Func<int, IEnumerable<MyClass>>), this, mi);
于 2012-10-17T16:42:19.927 回答