整理自http://bbs.csdn.net/topics/390622815
回调函数,这一般是在C语言中这么称呼,对于定义一个函数,但是并不由自己去调用,而是由被调用者间接调用,都可以叫回调函数。本质上,回调函数和一般的函数没有什么区别,也许只是因为我们定义了一个函数,却从来没有直接调用它,这一点很奇怪,所以有人发明了回调函数这个词来统称这种间接的调用关系。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
Action foo1 = () =>
{
int i = 1;
Action foo2 = () =>
{
int j = 2;
Action foo3 = () =>
{
int k = 3;
Console.WriteLine(i + j + k);
};
foo3();
// error Console.WriteLine(k);
};
foo2();
// error Console.WriteLine(j);
};
foo1();
// error Console.WriteLine(i);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
class A
{
static public Action action;
}
class Program
{
void foo()
{
int i = 1;
A.action = () => Console.WriteLine(i); //很明显,i这个变量按理说在foo()执行完了以后就没用了,但是当我们在匿名函数中访问它以后,它在函数退出之后仍然有效。
}
void bar()
{
A.action();
}
void Main()
{
foo();
bar();
}
}
|
1
2
3
4
5
6
7
|
void PrintElementsInTheArray( int [] array)
{
for ( int i = 0; i < array.GetLength(0); i++)
{
Console.WriteLine(array[i]);
}
}
|
1
2
3
4
5
6
7
8
|
void PrintElementsInTheArray2( int [] array)
{
for ( int i = 0; i < array.GetLength(0); i++)
{
if (i == 0) Console.Write(array[i]);
else Console.Write( "," + array[i]);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
void PrintElementsInTheArray( int [] array, bool SplitByComma)
{
for ( int i = 0; i < array.GetLength(0); i++)
{
if (SplitByComma)
{
if (i == 0) Console.Write(array[i]);
else Console.Write( ", " + array[i]);
}
else
{
Console.WriteLine(array[i]);
}
}
}
|
1
2
3
4
5
6
7
|
void PrintElementsInTheArray( int [] array, Action< bool , int > action)
{
for ( int i = 0; i < array.GetLength(0); i++)
{
action(i == 0, array[i]);
}
}
|
1
|
PrintElementsInTheArray(data, (isFirst, item) => Console.WriteLine(item));
|
1
2
3
|
PrintElementsInTheArray(data, (isFirst, item) => {
if (isFirst) Console.Write(item); else Console.Write( ", " + item);
});
|
1
|
PrintElementsInTheArray(data, (isFirst, item) => Response.WriteLine(item));
|
1
2
3
4
5
|
//在另一个很远的地方
public const int MaxLength = 2;
...
int [] arr = new int [MaxLength];
int i = arr[3];
|
1
2
|
int [] arr = new int [2];
int i = arr[3];
|