欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2008年03月14日 19:01:27   作者:  
jQuery中使用each(callback)方法可以很方便的遍歷集合,如

$("img").each(function(i){ 
this.src = "test" + i + ".jpg"; 
});  


就可以給給所有圖像設(shè)置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)比起來(lái)還顯得復(fù)雜了點(diǎn)。

現(xiàn)在使用c#3.0的擴(kuò)展方法功能來(lái)將each(callback)移植到c#中來(lái)。然后我們就可以用這段代碼替換上面的了。


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



比f(wàn)oreach簡(jiǎn)便多了吧,實(shí)現(xiàn)代碼就幾行。

    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); 
            } 
        } 
    } 

相關(guān)文章

最新評(píng)論