C#的委托

委托:顾名思义,让别人帮你办件事。委托是C#实现回调函数的一种机制。可能有人会问了,回调函数是个啥???

举个例子:我现在是一家公司的老板,公司现在在招聘.NET工程师,我们有一个小姐姐专门负责接受求职者投递的简历,我就告诉这个小姐姐,一旦收到新的简历就转发给我一份。

这个例子里小姐姐要做的工作:给我转发一份简历(回调函数里的操作),就是一个回调函数的作用。一旦有了满足条件(收到了新的简历),小姐姐就会转发给我(触发回调函数)

以上文章 转载为 千金不如一默 以下为原创

Action<string> CR = obj => MessageBox.Show(obj);//给他一个临时的obj作为接受值然后callaction的方法obj来接收收到的值
Action<string> CRA = new Action<string>(showmsg);//也可以这样写 
new Action<object>((object err) =>MessageBox.Show((string)err))("");
CR("1");
//action委托用来代理一个任意过程给过程一个值=>指向一个方法然后就可以调用//action没有返回值

//Delegate无法在过程里声明必须声明全局

//Delegate委托是最广泛的他支持全部过程但是并没有上下两个精简和效率

MyDelegate mydelegate = new MyDelegate(s => GetStr(s));
MyDelegate mydelegateA = new MyDelegate(GetStr);//也可以这样写
string get = mydelegate(1);


//func 委托用来执行一个没有传参且有返回值的过程
Func<string> getstr = new Func<string>(showmsgA);
string getAAA = getstr();

下面为一个委托演示

private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "";
            PictureBox pic = new PictureBox();

            pic.Width = 0;
            pic.Height = this.Height;
            pic.BackColor = Color.Red;
            this.Controls.Add(pic);
            label1.Parent = this;
            label1.SendToBack();
            if (maxthread == 0) {

                new Thread(() => {
                    maxthread++;
                    while (pic.Width < this.Width)
                    {
                        Thread.Sleep(1);
                        pic.BeginInvoke(new Action(() => { pic.Width = pic.Width + 2; }));
                    }
                    Thread.Sleep(1000);
                    CheckForIllegalCrossThreadCalls = false;
                    Random rd = new Random();
                    int getjl = rd.Next(0, 100);
                    //100

                    if (getjl < 5)
                    {
                        label1.Text = "中大奖";

                    }

                    if (getjl < 10 && getjl >5)
                    {
                        label1.Text = "电冰箱";

                    }

                    if (getjl <= 100 && getjl > 10)
                    {
                        label1.Text = "未中奖";

                    }

                    while (pic.Width > 0)
                {
                    pic.BackColor = Color.Black;
                    Thread.Sleep(1);
                    pic.BeginInvoke(new Action(() => { pic.Width = pic.Width - 2; }));
                }


                maxthread--;

            }).Start();

            }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值