[英]c# methods within methods
In Delphi, you can define functions within functions, example : 在Delphi中,您可以在函数中定义函数,例如:
function Foo : integer;
var myvar : integer;
function Foo1;
begin
myvar := 42;
end;
begin
result := myvar;
end;
This returns 42 as expected because Foo1 has access to Foo's myvar. 这会按预期返回42,因为Foo1可以访问Foo的myvar。
Is there any equivalent in C#? C#中有没有相应的东西?
Yes, there are many ways to do this. 是的,有很多方法可以做到这一点。 One way is to declare Func or Action delegates as follows: 一种方法是声明Func或Action委托如下:
void Foo()
{
Func<int,int> f = x => x+1;
//or
Func<int,int> ff = x => {
return x+1;
};
var r = f(1); //2
var rr = ff(2); //3
Func<int,int,int> add => (a,b) => a+b;
var rrr = add(2,3); //5
}
The shorthand declaration ( =>
) is commonly used in Linq. 简写声明( =>
)常用于Linq。 See lambdas . 见lambdas 。
There are many generic Func
and Action
delegates declared in the BCL (or whatever it's called nowdays) to allow for all but the stupidest length parameter lists. 在BCL(或称为nowdays)中声明了许多通用的Func
和Action
委托,以允许除了最愚蠢的长度参数列表之外的所有参数。 You could always declare your own generic delegates if you need more parameters. 如果需要更多参数,可以随时声明自己的通用委托。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.