【问题标题】:Returning a function with the same signature as itself in C#在 C# 中返回与自身具有相同签名的函数
【发布时间】: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&lt;C&gt;),但这不能用于模拟这一点(除非非常笨拙,IFunc 具有 @987654327 @ 方法等)。当然,您可以通过使用objectdynamic 或同样不明确的方式作为转换前的返回类型,以非类型安全的方式实现此目的。您也可以将它包装在一个类中,这可以很好地返回自身。你只是不能使用通用的Func 来做到这一点。

标签: c# types recursive-datastructures


【解决方案1】:

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

public delegate RecursiveType RecursiveType(int x);

然后这将编译:

RecursiveType currentStep = Foo.fun(1);
var i = 0;
while (currentStep != null)
{
    currentStep = currentStep(i);
    i += 1;
}

委托代表一个接受int并返回相同签名的函数的函数。

【讨论】:

  • 聪明。我忘了递归委托类型是一回事。结合方法组转换(和其他委托转换),您可以或多或少地直接执行此操作(Foo.fun 内的return Foo.fun 可以工作)。
  • @JeroenMostert 是的,或者假设Foo.A 也接受int 并按照OP 的建议返回RecursiveType
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多