现在的位置: 首页 > 综合 > 正文

关于C#闭包

2012年10月23日 ⁄ 综合 ⁄ 共 2049字 ⁄ 字号 评论关闭

先看程序:

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleTets
{
class Program
{
static void Main(string[] args)
{
string srcStr = "新洲区_武汉,黄浦区_上海,洪山区_武汉,崇安区_无锡,黄陂区_武汉,滨湖区_无锡";
string cityName = "武汉,无锡,上海";

string[] citysArr = cityName.Split(',');
IEnumerable
<string>[] areaName = new IEnumerable<string>[citysArr.Length];
int count = 0;
for(;count<citysArr.Length;count++)
{
areaName[count]
= srcStr.Split(',').Where(a => a.Contains(citysArr[count])).Distinct();
}
//Console.WriteLine(count);
Console.Read();
}
}
}

最后areaName[0],areaName[1],areaName[2]的值都为"黄浦区_上海"。

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleTets
{
class Program
{
static void Main(string[] args)
{
string srcStr = "新洲区_武汉,黄浦区_上海,洪山区_武汉,崇安区_无锡,黄陂区_武汉,滨湖区_无锡";
string cityName = "武汉,无锡,上海";

string[] citysArr = cityName.Split(',');
IEnumerable
<string>[] areaName = new IEnumerable<string>[citysArr.Length];
int count = 0;
for (; count < citysArr.Length; count++)
{
int temp = count;
areaName[count]
= srcStr.Split(',').Where(a => a.Contains(citysArr[temp])).Distinct();
}
//Console.WriteLine(count);
Console.Read();

}
}
}

这个就能得到想要的结果。

我的帖子:

http://topic.csdn.net/u/20091214/23/dddde3da-a064-436a-bf47-830dc80b7690.html

还没完全弄明白,不敢下定论,先留位。

类似问题的文章及讨论:

http://topic.csdn.net/u/20090821/13/7c30e8cb-3d37-4d4f-9c11-0df1dd7be8f4.html

http://www.cnblogs.com/foundation/archive/2008/12/11/1352797.html

http://www.cnblogs.com/qishichang/archive/2009/06/20/1507540.html

http://www.cnblogs.com/Klesh/archive/2008/05/15/The-Beauty-of-Closures.html

http://www.kuqin.com/dotnet/20080421/7169.html

比较赞同第二个链接中的观点:

      “ 若匿名方法中引用了某个变量,则该局部变量将被提升为实例变量,并储存于一个叫做闭包(closure)的对象中。提升之后,即使创建该变量的方法执行完毕该变量仍不会消亡。当指向该匿名函数的所有引用都消失后,该闭包变量即可正常地被垃圾回收器回收。闭包中参数或内部变量不是放在栈中,而是放在程序执行过程之中的一张全局表里。

       局部变量是通过变成对象的实例字段延长的生命期。编译器自动生成嵌套类,并把局部变量的值给了嵌套类的对象,等方法调用的时候,再从对象中取出来。”

补充:

        srcStr.Split(',').Where(a => a.Contains(citysArr[temp])).Distinct();  就是一个匿名方法,之所以使用temp可以得到正确的结果,是因为temp每次都重新开辟空间。

什么是闭包? 

        简单来讲,闭包允许你将一些行为封装,将它像一个对象一样传来递去,而且它依然能够访问到原来第一次声明时的上下文。这样可以使控制结构、逻辑操作等从调用细节中分离出来。访问原来上下文的能力是闭包区别一般对象的重要特征,尽管在实现上只是多了一些编译器技巧。

抱歉!评论已关闭.