0

这是我的场景:

Class Test  
{  
    public int TestMethod(string s)  
    {
        return s.length; 
    }  

    public void TestInvoker()  
    {    
        var result = Invoker.Call( (new Test()).TestMethod,"String");  
    }  
}

Class Invoker  
{  
    public static object Call(Delegate method, object input) {... Do stuff ...} 

}  

我怎样才能做到这一点?因为“TestMethod”不是一个委托,我可以用 Func<> 来做,但我想避免在每次使用调用程序时实例化一个 Func<> 委托。

这可能吗?

4

1 回答 1

2

这是可能的,但前提是该方法接受具体的委托类型;不是Delegate自己。

如果您将方法更改为

public static TReturn Call<TInput, TReturn>(Func<TInput, TReturn> method, TInput input)

,它会正常工作。


更准确地说,C# 具有从方法组到匹配委托类型的隐式转换。

于 2013-01-22T20:58:19.877 回答