在C#中返回具有与其自身相同签名的函数

问题描述

在我的应用程序中,我想要一个函数,该函数在完成一些工作后返回一个具有与自身相同的签名的函数,或者返回null: 请注意,这里没有泛型,因为所有类型都是“静态”的(例如,与泛型相反)

//type is not a C# keyword,but bear with me
type RecursiveType = Func<int,RecursiveType>;
RecursiveType currentStep; //something not null
var i = 0;
while (currentStep != null) {
    currentStep = currentStep(i);
    i += 1;
}

“ currentStep”将类似于(这是一个示例。在实际情况下,Foo :: A执行一些逻辑来确定它将返回哪个函数,并且可能本身也可能不是)

class Foo {
    public static RecursiveType fun(int x) {
        if (x < 3) { 
            return Foo.A
        }
        else {
            return null;
        }
    }
}

这在C#中可行吗?

解决方法

您可以这样声明一个委托类型:

.item1 {
    flex: 1;
}

然后它将编译:

public delegate RecursiveType RecursiveType(int x);

委托代表一个接受RecursiveType currentStep = Foo.fun(1); var i = 0; while (currentStep != null) { currentStep = currentStep(i); i += 1; } 并返回具有相同签名的函数的函数。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...