f
不能返回int
,因为调用f
一次后不能调用int
.不过,它可以返回包装int
的包装类型.f
只需要返回包装器类型,然后就可以无限链接.
如果您对索引器访问语法[...]
而不是方法调用语法(...)
感到满意,那么您只需创建一个 struct ,如下所示:
struct F {
public int Count { get; }
private F(int count) {
Count = count;
}
public F this[int acc] => new F(Count + acc);
// override ToString to return Count.ToString,
// or an implicit conversion to int, if you want
}
然后,
F f = new F(); // this could be a static field somewhere, making it effectively a global variable
Console.WriteLine(f[1][2][3][4].Count);
如果您真的喜欢方法调用语法,则需要使用dynamic
并从DynamicObject
继承,覆盖TryInvoke
,就像在this answer中一样.
示例:
dynamic f = new F();
Console.WriteLine(f(1)(2)(3)(4).Count);
class F: DynamicObject {
public int Count { get; }
public F(int count = 0) {
Count = count;
}
public override Boolean TryInvoke(InvokeBinder binder, object?[]? args, out object? result) {
if (args?.Length == 1 && args?[0] is int acc) {
result = new F(Count + acc);
return true;
}
result = null;
return false;
}
}