C# 自己对delegate的总结和认识

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace LamdaSimple
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private delegate double MathAction(double num);

        private double Double(double input)
        {
            return input * 2;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //MSDN上例子:http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ZH-CN&k=k(DELEGATE_CSHARPKEYWORD);k(DELEGATE)&rd=true
            // Instantiate delegate with named method:委托
            MathAction ma = Double;
            // Invoke delegate ma:
            double multByTwo = ma(4.5);
            Console.WriteLine(multByTwo);

            // Instantiate delegate with anonymous method:匿名方法
            MathAction ma2 = delegate(double input)
            {
                return input * input;
            };
            double square = ma2(5);
            Console.WriteLine(square);

            // Instantiate delegate with lambda expression:Lambda表达式
            MathAction ma3 = (s) =>
            {
                return s * s;
            };

            PrintAction((s) =>
            {
                return s * s;
            });

            //**************************************************************
            //参数为:Delegate method;才可以进行new Action
            Thread t = new Thread(() => this.textBox1.Invoke(new Action(() =>
            {
                for (int i = 0; i < 50; i++)
                {
                    this.textBox1.Text = i.ToString();
                }
            })));
            t.Start();

            //**************************************************************
            //s => s + s; s=>{ return s+ s;} 相当于
            List<string> lst = new List<string>();
            var v = lst.Select(s => { return s; });
            var v1 = lst.Select(s => s + 10);

            List<Student> lstStundets = new List<Student>();
            var v2 = lstStundets.Select(s =>
            {
                return new
                {
                    aaa = s.ID,
                    bbbb = s.Name
                };
            });
            //等于
            var v3 = lstStundets.Select(s =>
            new
            {
                aaa = s.ID,
                bbbb = s.Name
            });

            //**************************************************************
            //当只有一个参数的时候
            lstStundets.ForEach(s =>
            {
                s.ID = "";
                s.Name = "";
            });

            lstStundets.ForEach((s) =>
            {
                s.ID = "";
                s.Name = "";
            });

            lstStundets.ForEach((s) =>
            {
                s.ID = "";
                s.Name = "";
            });

            try
            {
                var intValue = this.textBox1.GetValue<int>();
            }
            catch (Exception)
            {
            }
        }

        public void PrintAction(Func<double, double> ation)
        {
        }
    }

    public class Student
    {
        public string ID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }
    }

    public static class Exstions
    {
        ///默认版本,调用上个重载方法

        public static TResult GetValue<TResult>(this TextBox textBox)
                    where TResult : struct
        {
            return GetValue<TResult>(textBox, true);
        }

        public static TResult GetValue<TResult>(this TextBox textBox, bool isShowError)
            where TResult : struct
        {
            return GetValue<TResult>(textBox, (p) =>
            {
                if (isShowError)
                {
                    p.Focus();
                    p.SelectAll();
                    MessageBox.Show("输入值格式不正确,请重新输入!",
                        "提示--值类型:" + typeof(TResult).Name,
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            });
        }

        //ailed(textBox); 可以这样理解。
        //委托指向方法;相当于一个不返回值,参数为TextBox的方法。如下:
        public static void ExecutAction(TextBox textBox)
        {
            textBox.Focus();
            textBox.SelectAll();
        }

        public static TResult GetValue<TResult>(this TextBox textBox, Action<TextBox> failed)
            where TResult : struct
        {
            var type = typeof(TResult);
            var method = type.GetMethod("TryParse", new Type[] { typeof(string), type.MakeByRefType() });
            var parameters = new object[] { textBox.Text, default(TResult) };

            // 若转换失败,执行failed
            if (!(bool)method.Invoke(null, parameters))
            {
                failed(textBox);
                throw new InvalidCastException("输入值格式不正确,请检查输入值。");
            }

            return (TResult)parameters[1];
        }
    }
}

  代码下载:http://files.cnblogs.com/zfanlong1314/LamdaSimple.zip

原文地址:https://www.cnblogs.com/51net/p/3908659.html