雁过请留痕...
代码改变世界

扩展方法及几种常见的代理(delegate)语法

2012-06-05 11:27  xiashengwang  阅读(387)  评论(0编辑  收藏  举报

1,扩展方法必须写在非泛型的静态类中

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

namespace Cshapr3._0NewFeature
{
    public static class ExtendMethod
    {
        //Search Control's Child
        public static IEnumerable<T> SearchControls<T>(this Control control, Func<T, bool> filter, bool searchChild)
            where T : Control
        {
            foreach (Control child in control.Controls)
            {
                if (child is T && (filter == null || filter(child as T)))
                    yield return (T)child;

                if (searchChild)
                {
                    foreach (T t in SearchControls<T>(child, filter, searchChild))
                    {
                        yield return t;
                    }
                }
            }
        }

        //Enum Collection's member
        public static void ForEach<T>(this IEnumerable<T> enumer, Action<T> action)
        {
            foreach (var item in enumer)
            {
                action(item);
            }
        }
    }
}

2,常见的delegate语法

 分别用了Lamda,委托的方法组转换,委托,匿名方法四种形式调用

            //Lamda Expression
            this.SearchControls<Button>(c=>c.Name =="button1"||c.Name =="button1", true).ForEach(c => this.textBox2.Text += c.Name + Environment.NewLine);
            //Delegate(method group conversion)
            this.SearchControls<Button>(SearchNeededButton, true).ForEach(c => this.textBox2.Text += c.Name + Environment.NewLine);
            //Delegate
            this.SearchControls<Button>(new Func<Button,bool>(SearchNeededButton), true).ForEach(c => this.textBox2.Text += c.Name + Environment.NewLine);
            //anonymous method
            this.SearchControls<Button>(delegate(Button b) { if (b.Name == "button1" || b.Name == "button2")return true; return false; }, true).ForEach(c => this.textBox2.Text += c.Name + Environment.NewLine);
        private bool SearchNeededButton(Button button)
        {
            if (button.Name == "button1" || button.Name == "button2")
                return true;
            return false;
        }