2012-10-17 88 views
2

运行Run2方法。但Run方法不运行。是什么原因 ? 两种方法之间的唯一区别是因为参数。为什么我使用Delegate.CreateDelegate获得这个错误'绑定到目标方法'?

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

回答

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