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

简介: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.
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

目录
相关文章
|
5天前
|
弹性计算 人工智能 安全
云上十五年——「弹性计算十五周年」系列客户故事(第二期)
阿里云弹性计算十五年深耕,以第九代ECS g9i实例引领算力革新。携手海尔三翼鸟、小鹏汽车、微帧科技等企业,实现性能跃升与成本优化,赋能AI、物联网、智能驾驶等前沿场景,共绘云端增长新图景。
|
11天前
|
存储 弹性计算 人工智能
【2025云栖精华内容】 打造持续领先,全球覆盖的澎湃算力底座——通用计算产品发布与行业实践专场回顾
2025年9月24日,阿里云弹性计算团队多位产品、技术专家及服务器团队技术专家共同在【2025云栖大会】现场带来了《通用计算产品发布与行业实践》的专场论坛,本论坛聚焦弹性计算多款通用算力产品发布。同时,ECS云服务器安全能力、资源售卖模式、计算AI助手等用户体验关键环节也宣布升级,让用云更简单、更智能。海尔三翼鸟云服务负责人刘建锋先生作为特邀嘉宾,莅临现场分享了关于阿里云ECS g9i推动AIoT平台的场景落地实践。
【2025云栖精华内容】 打造持续领先,全球覆盖的澎湃算力底座——通用计算产品发布与行业实践专场回顾
|
2天前
|
云安全 人工智能 安全
Dify平台集成阿里云AI安全护栏,构建AI Runtime安全防线
阿里云 AI 安全护栏加入Dify平台,打造可信赖的 AI
|
9天前
|
人工智能 自然语言处理 自动驾驶
关于举办首届全国大学生“启真问智”人工智能模型&智能体大赛决赛的通知
关于举办首届全国大学生“启真问智”人工智能模型&智能体大赛决赛的通知
|
5天前
|
人工智能 运维 Java
Spring AI Alibaba Admin 开源!以数据为中心的 Agent 开发平台
Spring AI Alibaba Admin 正式发布!一站式实现 Prompt 管理、动态热更新、评测集构建、自动化评估与全链路可观测,助力企业高效构建可信赖的 AI Agent 应用。开源共建,现已上线!
477 14
|
4天前
|
编解码 文字识别 算法
一张图能装下“千言万语”?DeepSeek-OCR 用视觉压缩长文本,效率提升10倍!
一张图能装下“千言万语”?DeepSeek-OCR 用视觉压缩长文本,效率提升10倍!
372 10
|
10天前
|
编解码 自然语言处理 文字识别
Qwen3-VL再添丁!4B/8B Dense模型开源,更轻量,仍强大
凌晨,Qwen3-VL系列再添新成员——Dense架构的Qwen3-VL-8B、Qwen3-VL-4B 模型,本地部署友好,并完整保留了Qwen3-VL的全部表现,评测指标表现优秀。
679 7
Qwen3-VL再添丁!4B/8B Dense模型开源,更轻量,仍强大
|
12天前
|
机器学习/深度学习 缓存 自然语言处理
【万字长文】大模型训练推理和性能优化算法总结和实践
我们是阿里云公共云 AI 汽车行业大模型技术团队,致力于通过专业的全栈 AI 技术推动 AI 的落地应用。
594 36
【万字长文】大模型训练推理和性能优化算法总结和实践