【问题标题】:How do I declare a Func Delegate which returns a Func Delegate of the same type?如何声明一个返回相同类型的 Func Delegate 的 Func Delegate?
【发布时间】:2015-01-17 01:27:19
【问题描述】:

我想编写一个方法来完成一些工作并最终返回另一个与原始方法具有相同签名的方法。这个想法是根据前一个字节值顺序处理字节流,而不需要递归。像这样调用它:

MyDelegate executeMethod = handleFirstByte //What form should be MyDelegate?

foreach (Byte myByte in Bytes)
{
    executeMethod = executeMethod(myByte); //does stuff on byte and returns the method to handle the following byte
}

要移交我想将它们分配给 Func 委托的方法。但是我遇到了一个问题,这会导致递归声明没有终止......

Func<byte, Func<byte, <Func<byte, etc... >>>

我不知何故迷路了。我怎么能解决这个问题?

【问题讨论】:

    标签: c# delegates func


    【解决方案1】:

    当预定义的Func&lt;...&gt; 委托不足时,您可以简单地声明一个委托类型:

    public delegate RecursiveFunc RecursiveFunc(byte input);
    

    如果你需要它,你也可以使用泛型:

    public delegate RecursiveFunc<T> RecursiveFunc<T>(T input);
    

    【讨论】:

    • 方法的签名在编译时是未知的。他不知道参数是Byte
    • @Servy 在那种情况下...delegate RecursiveFunc&lt;T&gt; RecursiveFunc&lt;T&gt;(T input)
    • 优秀 - 像魅力一样工作。就我而言,我知道它将是一个字节,但通用版本 +1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多