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


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值