zoukankan      html  css  js  c++  java
  • 扩展方法及几种常见的代理(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;
            }
  • 相关阅读:
    jmeter之三种参数化
    linux(centos6.5)常用命令
    win10+jdk+mysql+tomcat+jpress环境搭建与部署
    [剑指Offer] 29.最小的K个数
    [C/C++] C++中new的语法规则
    [C/C++] 深拷贝和浅拷贝
    [C/C++] #ifdef和#endif
    [C/C++] C++声明和定义的区别
    [C/C++] extern关键字详解以及与static、const区别
    [C/C++] static在C和C++中的用法和区别
  • 原文地址:https://www.cnblogs.com/xiashengwang/p/2578784.html
Copyright © 2011-2022 走看看