随笔 - 78  文章 - 25  trackbacks - 0
<2009年10月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

常用链接

留言簿

随笔分类(75)

随笔档案(78)

相册

实用Links

我的Links

搜索

  •  

积分与排名

  • 积分 - 112098
  • 排名 - 521

最新评论

阅读排行榜

评论排行榜

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

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
**********************



posted on 2009-10-26 15:59 期待明天 阅读(244) 评论(0)  编辑  收藏 所属分类: CSharp

只有注册用户登录后才能发表评论。


网站导航: