C#学习笔记——委托机制


什么是委托?
委托仅仅是函数指针,那就是说,它能够引用函数,通过传递地址的机制完成。委托是一个类,当你对它实例化时,要提供一个引用函数,将其作为它构造函数的参数
委托具有以下特点:
1)委托类似于 C++ 函数指针,但它是类型安全的。
2)委托允许将方法作为参数进行传递。
3)委托可用于定义回调方法。
4)委托可以链接在一起;例如,可以对一个事件调用多个方法。
5)方法不需要与委托签名精确匹配。有关更多信息,请参见协变和逆变。
6)C# 2.0 版引入了匿名方法的概念,此类方法允许将代码块作为参数传递,以代替单独定义的方法。

定义和使用委托分四个步骤:
1、委托定义 2、委托声明。3、委托实例化。4、委托调用。
示例代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//引入命名空间
using System.Threading;
 
namespace CSharp_001_委托机制
{
    public partial class frmMain : Form
    {
        //定义委托
        private delegate void SetValueDelegate(int value);
        //声明委托
        SetValueDelegate setValue;
 
        public frmMain()
        {
            InitializeComponent();
        }
 
        private void btnStart_Click(object sender, EventArgs e)
        {
            //实例化委托
            setValue = new SetValueDelegate(SetProgreesBarValue);
            SetProgreesBarValueMethod(setValue);
            //实例化委托
            setValue = new SetValueDelegate(SetLabTextValue);
            SetProgreesBarValueMethod(setValue);
        }
 
        void SetProgreesBarValueMethod(SetValueDelegate SetValue)
        {
            for (int i = 0; i <= 100; i++)
            {
                Application.DoEvents();
                Thread.Sleep(50);
                SetValue(i);
            }
        }
        void SetProgreesBarValue(int value)
        {
            pgProgressBar.Value = value;
        }
        void SetLabTextValue(int value)
        {
            labText.Text = value.ToString();
        }
    }
}

示例结果:

image

原文地址:https://www.cnblogs.com/hanzhaoxin/p/2914439.html