且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-17 09:20:27

什么是委托?
委托仅仅是函数指针,那就是说,它能够引用函数,通过传递地址的机制完成。委托是一个类,当你对它实例化时,要提供一个引用函数,将其作为它构造函数的参数
委托具有以下特点:
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();
        }
    }
}

示例结果:

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

作者:韩兆新
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
标签: C#学习笔记

本文转自韩兆新博客博客园博客,原文链接:http://www.cnblogs.com/hanzhaoxin/archive/2013/02/17/2914439.html,如需转载请自行联系原作者