一个C#方法可以返回一个方法? [英] Can a C# method return a method?

查看:596
本文介绍了一个C#方法可以返回一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



有一个方法可以返回的 lambda表达式例如,但我不知道我可以给什么样的类型参数的这种方法,因为方法不键入 。这样返回的方法可能被分配给一些代表。



考虑这个概念作为一个例子:

 公众和LT;未知类型> QuadraticFunctionMaker(浮动,浮动B,浮动三)
{
则返回(x)=> {返回* X * X + B * X + C; };
}

代表浮动功能(浮X);
功能QuadraticFunction = QuadraticFunctionMaker(1F,4F,3F);


解决方案

您正在寻找的类型是动作<> Func键<>



通用参数关于这两种类型的确定方法的类型签名。如果你的方法没有返回值使用动作。如果有使用函数功能即最后一个泛型参数是返回类型



例如:



 公共无效DoSomething的()//动作
公共无效DoSomething的(INT数)//动作< INT>
公共无效DoSomething的(整型数字,字符串文本)//动作< INT,串>

公众诠释DoSomething的()//函数功能:LT; INT>
公众诠释DoSomething的(INT数)//函数功能:LT; INT,INT>
公众诠释DoSomething的(整型数字,字符串文本)//函数功能:LT; INT,字符串,整数>


Can a method in C# return a method?

A method could return a lambda expression for example, but I don't know what kind of type parameter could I give to such a method, because a method isn't Type. Such a returned method could be assigned to some delegate.

Consider this concept as an example:

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);

解决方案

The Types you are looking for are Action<> or Func<>.

The generic parameters on both types determine the type signature of the method. If your method has no return value use Action. If it has use Func whereby the last generic parameter is the return type.

For example:

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(int number)               // Func<int,int>
public int DoSomething(int number, string text)  // Func<int,string,int>

这篇关于一个C#方法可以返回一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆