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;
            }
  • 相关阅读:
    android签名文件(.keystore)
    server2008部署网狐荣耀遇到的问题
    网关详解
    服务端架构
    rest service下载文件与上传
    mysql 按类别之用一条SQL语句查询出每个班前10名学生数据
    windows mysql 和linux mysql解决乱码问题
    关于redis的安装
    收藏nginx学习
    linux在tomcat中指定jdk
  • 原文地址:https://www.cnblogs.com/xiashengwang/p/2578784.html
Copyright © 2011-2022 走看看