【问题标题】:Is possible to pass a method as Delegate?是否可以将方法作为委托传递?
【发布时间】:2013-01-22 20:56:11
【问题描述】:

这是我的场景:

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 委托。

这可能吗?

【问题讨论】:

    标签: c# generics methods casting delegates


    【解决方案1】:

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

    如果您将方法更改为

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

    ,它会正常工作的。


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

    【讨论】:

    • 谢谢,我已经怀疑...但我认为可能存在一些可以解决问题的东西!谢谢!
    • 谢谢! =) 这就是我想避免“强制”Func 代表的原因。不过还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2011-12-04
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    相关资源
    最近更新 更多