简体   繁体   English

您如何返回Func <Func<string, int> ,int&gt;

[英]How do you return a Func<Func<string, int>, int>

I recently figured out how to return methods/functions from methods, for example: 我最近想出了如何从方法中返回方法/函数,例如:

public static Func<string, int> Parse() {
    return x => Int32.Parse(x);
}

Out of pure curiosity I wanted to know how far I can go. 出于好奇,我想知道我能走多远。 Is it possible to somehow return a Func<Func<string, int>, int> ? 是否有可能以某种方式返回Func<Func<string, int>, int>

public static Func<Func<string, int>, int> PlusSomething(this Func<string, int> parser) {
    return x => x + parser; //Obviously doesn't work
}



The closest thing I managed to do was 我最想做的是

public static Func<string, int, int> PlusSomething(this Func<string, int> parser) {
    return (x, y) => parser(x) + y;
}

Since it is not very clear what you want to achieve I am going to do a bit of guess work. 由于尚不清楚您要实现什么目标,我将做一些猜测工作。

A Func<Func<string, int>, int> is a function that takes a function and returns an int. Func<Func<string, int>, int>是一个接受一个函数并返回int的函数。

One possibility is that you want to return a function that takes a function f , applies it to a string and returns an int. 一种可能是您想返回一个接受函数f的函数,将其应用于字符串并返回一个int值。 In this case you have to specify somewhere on what you want to apply the function f . 在这种情况下,您必须在要应用功能f地方指定一个位置。 Either when you generate the function 生成函数时

public static Func<Func<string, int>, int> PlusSomething(string s) {
    return f => f(s);
}

either when you apply the function 当您应用功能时

public static Func<Func<string, int>, int, int> PlusSomething() {
    return f, s => f(s);
}

Looking at your second example it seems to me (I may be wrong) that you actually want to return a function that takes a int and return a function. 在您的第二个示例中,在我看来(我可能错了),您实际上想要返回一个带有int的函数并返回一个函数。

public static Func<int, Func<string, int>> PlusSomething(Func<string, int> parser) {
    return x => (y => x + parser(y));
}

This would allow something like 这将允许类似

var gen = PlusSomething(parser);
var parsePlus4 = gen(4);
int x = parsePlus4("8"); // x == 12

To answer the question as it is stated - yes, it is possible to have a function with the described signature as follows. 要回答所陈述的问题-是的,可以具有如下所述签名的功能。

public static
Func<Func<string,int>,int>
PlusSomething(this Func<string, int> parser)
{
    return x => 1;
}

However it is unclear what the desired result is and how the input should relate to the desired output; 但是,尚不清楚期望的结果是什么以及输入应如何与期望的输出相关; syntactically it is possible. 在语法上是可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM