C#函数委托

委托是一种动态调用函数的方式,通过委托可以将一些相同类型的函数串联起来依次执行。委托是函数回调和事件机制的基础。
委托,通过delegate关键字来声明,通过new,+=,-=运算符为其分配函数。
delegate void StrParaFunc(int no,string str);//定义一个委托,没有返回值,依次包含两个数据类型为int和string的参数

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace useDelegate
{
    
class  Program
    {
        
// / <summary>
         // / 定义委托
         // / </summary>
         // / <param name="no"></param>
         // / <param name="str"></param>
        delegate  void  StrParaFunc( int  no, string str);

        
static   void  PrintString( int  no, string str) {
            System.Console.WriteLine(
" {0}:PrintString:{1} " ,no,str);
        }
        
static   void  ShowString( int  no, string str)
        {
            System.Console.WriteLine(
" {0}:ShowString:{1} " , no, str);
        }
        
static   void  Main(string[] args)
        {
            
// 通过new初始化委托
            System.Console.WriteLine( " ********************** " );
            StrParaFunc spfHandler1 
=   new  StrParaFunc(PrintString);
            System.Console.WriteLine(
" 第一个委托对象,有1个引用函数: " );
            spfHandler1(
1 , " a string 1 " ); // 委托类型中有一个引用函数,结果有1个    
            System.Console.WriteLine( " ********************** " );
            
            spfHandler1 
+=  ShowString; // 通过+=增加引用函数
            System.Console.WriteLine( " 第一个委托对象,增加了一个引用函数,共2个引用函数: " );
            spfHandler1(
2 , " a string 2 " ); // 委托中有两个引用函数,结果有2个       
            System.Console.WriteLine( " ********************** " );

            spfHandler1 
-=  PrintString;  // 通过-=移除引用函数      
            System.Console.WriteLine( " 第一个委托对象,减少了一个引用函数,剩1个引用函数: " );
            spfHandler1(
3 " a string 3 " );  // 委托中有一个引用函数,结果1个
            System.Console.WriteLine( " ********************** " );

            
// 通过函数地址直接初始化委托
            StrParaFunc spfHandler2  =  PrintString;
            spfHandler2(
4 " a string 4 " );
            System.Console.WriteLine(
" ********************** " );
            System.Console.ReadLine();
        }
    }
}

运行结果:

**********************
第一个委托对象,有1个引用函数:
1:PrintString:a string 1
**********************
第一个委托对象,增加了一个引用函数,共2个引用函数:
2:PrintString:a string 2
2:ShowString:a string 2
**********************
第一个委托对象,减少了一个引用函数,剩1个引用函数:
3:ShowString:a string 3
**********************
4:PrintString:a string 4
**********************



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值