C#方法可以返回一个方法吗?

kr8*_*r85 34 c# methods lambda return-type

C#中的方法可以返回一个方法吗?

例如,一个方法可以返回一个lambda表达式,但是我不知道我可以为这样的方法提供什么类型的参数,因为方法不是Type.这样的返回方法可以分配给某个委托.

以此概念为例:

public <unknown type> QuadraticFunctionMaker(float a , float b , float c)
{
    return (x) => { return a * x * x  + b * x + c; };
}

delegate float Function(float x);
Function QuadraticFunction = QuadraticFunctionMaker(1f,4f,3f);
Run Code Online (Sandbox Code Playgroud)

Zeb*_*ebi 38

您正在寻找的类型是Action<>Func<>.

两种类型的通用参数确定方法的类型签名.如果您的方法没有使用返回值Action.如果它具有返回值,则使用Func最后一个通用参数是返回类型.

例如:

public void DoSomething()                          // Action
public void DoSomething(int number)                // Action<int>
public void DoSomething(int number, string text)   // Action<int,string>

public int DoSomething()                           // Func<int>
public int DoSomething(float number)               // Func<float,int>
public int DoSomething(float number, string text)  // Func<float,string,int>
Run Code Online (Sandbox Code Playgroud)


sir*_*ide 20

public Func<float, float> QuadraticFunctionMake(float a, float b, float c) {
    return x => a * x * x + b * x + c;
}
Run Code Online (Sandbox Code Playgroud)

返回类型是Func<float, float>.