栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

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

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


$("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 arg); 
    public static class IEnumerableExtension 
    { 
        public static void Each(this IEnumerable src, EachDelegate callback) 
        { 
            foreach (T item in src) 
            { 
                callback(item); 
            } 
        } 
    } 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/59666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号