zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    python的编码判断_unicode_gbk/gb2312_utf8(附函数)
    stat文件状态信息结构体
    内核配置中 ramdisk 大小修改
    mount命令详解
    dirent和DIR 结构体 表示文件夹中目录内容信息
    nandwrite 参数
    mke2fs 制作ext2文件系统image
    ext2文件系统错误
    照度/感光度(Lux)
    摄像机的几个重要的技术指标
  • 原文地址:https://www.cnblogs.com/hanzhaoxin/p/2914439.html
Copyright © 2011-2022 走看看