当前位置: 移动技术网 > IT编程>开发语言>.net > 把jQuery的each(callback)方法移植到c#中

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

2018年04月22日  | 移动技术网IT编程  | 我要评论
$("img").each(function(i){  this.src = "test" + i + 

$("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); 
            } 
        } 
    } 

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网