当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > 把jQuery的each(callback)方法移植到c#中

ASP.NET
如何用Response.Redirect方法传递汉字
在ASP.NET中调用存储过程方法新解
决定何时使用 DataGrid、DataList 或 Repeater(ASP.NET 技术文章)
AlternatingItemTemplate类似于 ItemTemplate 元素
c#中过滤html的正则表达式
ASP.NET:ADO.NET的DataAdapter对象
repeater分页 内容显示
内容添加asp.net
VS2003 SP1发布
DataReader深入解析:持续更新
C#.Net 学习笔记(一)
从ASP过渡到ASP.net遗留的二十大积习
如何改变asp.net项目名称
asp,asp.net学习教程下载
基于.net开发的遵循web标准的个人站点程序包下载
FileUpload1 上传文件类型验证正则表达式
ASP.NET与数据库相关技巧
读取TXT文件内容的方法
简单的启动窗体
c#中实现文件拖放打开的方法

ASP.NET 中的 把jQuery的each(callback)方法移植到c#中


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 125 ::
收藏到网摘: n/a

jQuery中使用each(callback)方法可以很方便的遍历集合,如
$("img").each(function(i){
this.src = "test" + i + ".jpg";
});

就可以给给所有图像设置src属性。
c#中虽然有for(;;)和foreach(..in )可以完成此功能,
static void Main(string[] args)
{
string[] arr = new string[] { "A", "B", "C", "D", "E" };
foreach (string item in arr)
{
Console.WriteLine(item);
}
Console.ReadKey();
}

但和jQuery的each(callback)比起来还显得复杂了点。
现在使用c#3.0的扩展方法功能来将each(callback)移植到c#中来。然后我们就可以用这段代码替换上面的了。

static void Main(string[] args)
{
string[] arr = new string[] { "A", "B", "C", "D", "E" };
arr.Each(p => Console.WriteLine(p));
Console.ReadKey();
}

比foreach简便多了吧,实现代码就几行。
public delegate void EachDelegate<T>(T arg);
public static class IEnumerableExtension
{
public static void Each<T>(this IEnumerable<T> src, EachDelegate<T> callback)
{
foreach (T item in src)
{
callback(item);
}
}
}