【发布时间】:2020-08-18 12:30:36
【问题描述】:
在我的应用程序中,我想要一个函数,在完成一些工作后,返回一个与自身具有相同签名的函数,或者为 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# 中可行吗?
【问题讨论】:
-
你缺少新的:return new Foo.A() { set values};
-
Foo.A 不是一个类,它是一个函数(属于 A 类),所以我不能“新建”它。
-
是否总是有一个
int类型的参数?还是参数变量? -
总是一个
int参数。 -
递归类型在 .NET 的类型系统中不是一个东西。您可以获得的最接近的是在继承或约束子句中使用“作为自身”类型(
class C : IEquatable<C>),但这不能用于模拟这一点(除非非常笨拙,IFunc具有 @987654327 @ 方法等)。当然,您可以通过使用object或dynamic或同样不明确的方式作为转换前的返回类型,以非类型安全的方式实现此目的。您也可以将它包装在一个类中,这可以很好地返回自身。你只是不能使用通用的Func来做到这一点。
标签: c# types recursive-datastructures