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

  • 相关阅读:
    检测一个对象方法是否存在
    非堵塞 延迟脚本 高性能
    移动开发 相关 备忘
    元素透明 渐变函数
    cookie
    media query 单位
    前端入门可参考《如何教会非计算机专业的女友写代码》
    JQ判断复选框是否选中
    聊天记录
    JS获取文本值
  • 原文地址:https://www.cnblogs.com/hanzhaoxin/p/2914439.html
Copyright © 2011-2022 走看看