码迷,mamicode.com
首页 > 其他好文 > 详细

C#之委托初步

时间:2014-09-11 23:48:32      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   数据   

    传说中的东西,今天兴趣来了,就研究了研究,把大概什么是委托,如何使用委托稍微梳理了一下。

1、什么是委托

   首先,Class(类)是对事物的抽象,例如,哺乳动物都是胎生,那么你可以定义一个哺乳动物的基类,然后一大片的驴,马,狗,猪都从这继承而去。

   委托可以认为是同一类函数(function,也叫做方法)的抽象,代表的一系列同返回类型,同形参列表的函数。

   委托是个类型,就像int之流的一种类型。一个委托类型的变量可以指向一串同类型的函数,到时候需要调用这一串函数的时候,就可以调用这个委托类型的变量来使这些函数执行。

2、如何使用委托:

    先定义一个类,里面包含了一些具体的方法

bubuko.com,布布扣
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 //方法类就是需要实现具体功能的一些函数
 6 namespace DelegateTest
 7 {
 8     class Hit
 9     {
10         public void hitxiaoming()
11         {
12             Console.WriteLine("xiaoming was hited \n");
13         }
14         public void hitdahong()
15         {
16             Console.WriteLine("dahong was hitted\n");
17         }
18         public void hitxiaoweng()
19         {
20             Console.WriteLine("xiaoweng was hitted\n");
21         }
22     }
23 }
View Code

    在主程序中通过委托调用这三个函数,代码如下:

    主要分四步 声明委托类型,定义委托变量,绑定函数,调用委托

bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateTest
{
    class Program
    {
        delegate void hitSomeBody();//声明一个委托类型(不是变量)此时,hitSomeBody相当于数据类型,例如int
        private hitSomeBody hitone;//定义一个委托类型的变量,此时hitone是变量
        private Hit hit = new Hit();
        public void iniDelegate()
        {
            this.hitone += hit.hitdahong;//将函数绑定到委托变量中等效于hitone = new hitone(hitdahong);
            this.hitone += hit.hitxiaoming;
            this.hitone += hit.hitxiaoweng;
            hitone();//执行委托
        }
        static void Main(string[] args)
        {
            Program p = new Program();
           p.iniDelegate();
        }
       
    }
}
View Code

 

C#之委托初步

标签:style   blog   http   color   io   os   使用   ar   数据   

原文地址:http://www.cnblogs.com/tntboom/p/3967435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!