老农如是想,如是说,如是为
天才首页 > 博客 > 玩代码  >   .NET 委托 的简单解释  | 登录

   委托是.NET引进的一种极其类似中介的类型,其执行的基本原理就是,首先需要一个
返回数据的类型,执行参数的类型,然后就可以把这个委托指定到某个函数来执行,当
外部执行的时候看到的是委托的执行,看不到函数的执行。
其使用的方法简言之:
1:声明一个委托
2:创建一个委托需真正要执行的函数
3:执行委托即间接执行真实的业务。

例一:

声明一个委托:
public delegate void MyFirstDelegate(string sPut);

委托需要执行的中间层真实代码:

    public void FirstVoidFunction(string sPut){
        Console.WriteLine("Execute:FistVoidFunction({0})",sPut);
    }

创建一个委托实例并执行

        MyFirstDelegate ObjDele = new MyFirstDelegate(Obj.FirstVoidFunction);
        ObjDele("参数");

执行的结果

Execute:FistVoidFunction(参数)



例二,执行一个具有返回值的委托:

    public delegate int MySecondDelegate(int iPut);
    public int SecondIntFunction(int sPut){
        return sPut * sPut;
    }
    MySecondDelegate ObjDele2 = new MySecondDelegate(Obj.SecondIntFunction);
    int rId=ObjDele2(9);




关于委托,基本上就是这么回事,和接口是非常类似的。

关于更多,查看Delegate类。

另外本文的小例子。


using System;
using System.Collections.Generic;
using System.Text;

class DemoMain{
    public delegate void MyFirstDelegate(string sPut);
    public delegate int MySecondDelegate(int iPut);
    public static void Main(string[] args){
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("开始执行程序...");
        Console.ForegroundColor = ConsoleColor.White;

        DemoMain Obj =new DemoMain();
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("执行返回void的函数");
        Console.ForegroundColor = ConsoleColor.White;
        MyFirstDelegate ObjDele = new MyFirstDelegate(Obj.FirstVoidFunction);
        ObjDele("参数");

        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("执行返回Int的函数");
        Console.ForegroundColor = ConsoleColor.White;
        MySecondDelegate ObjDele2 = new MySecondDelegate(Obj.SecondIntFunction);
        Console.WriteLine("Execute:SecondIntFunction({0})={1}",9,ObjDele2(9));

        //Console.ReadLine();
    }
    public void FirstVoidFunction(string sPut){
        Console.WriteLine("Execute:FistVoidFunction({0})",sPut);
    }
    public int SecondIntFunction(int sPut){
        return sPut * sPut;
    }
}

天气:大雨,ccdot发表于2008-4-25 16:37:37,阅读了148次,共有个0回复.

暂无评论

  1. 顺其自然,不治而治.
  2. 不要提交任何带有网址URL信息的评论.
  3. 需要更多信息?请使用站内搜索,郁闷了?听听我在听什么吧!
用户名:*验证:看不清楚请点击刷新验证码*
内容:
青花瓷 边做边爱 征途 穷开心 摇啊摇 我们的歌 感动天感动地 白狐 自由飞翔 思念是一种病 分手那天 爱死了昨天
中国话 日不落 求佛 上海滩 等一分钟 天路 老人与海 左边 凤舞九天 有没有人告诉你 遇上你是我的缘 做你的爱人
拉拉爱 大悲咒 周杰伦 刘德华 命运 等爱的玫瑰 凤凰传奇 依然在一起 樱花草 dj flash 私服 为你写诗 你的承诺
杨惠妍 股票 博客 论坛 流行歌曲 小游戏 S.H.E 王力宏 博客 加盟 月亮之上 私服 彩虹 周笔畅 蔡依林 感恩的心
搞笑 流行音乐 mp3歌曲 mp3 股票 招商 歌曲mp3 双人小游戏 dj舞曲 最新歌曲 小游戏 美女 股票 dj mp3歌曲 mp3