C#中委托的运用

个人感觉委托其实说白了就是把一个方法当成参数来进行传递。比如说a,b两个人共同完成一个项目,其中a代码中需要用到b写的一个方法,但是此时b还没有写完,此时a只需要声明一个委托,定义好参数然后先使用,等b写好了再传递给a就可以了(比如类实例化的时候)。

 

例子:

soundDecoder.cs中需要用到b写的方法,先定义一个委托

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HikPlugin;

namespace SoundDecoder
{
    public class SoundDecodeProcesser
    {
             public delegate int Analyse(short[] buffer, int dvrCameraId);

             private Analyse analyse;

 

//对象初始化的时候可以传递方法

       public SoundDecodeProcesser(string dvrPassword, Analyse a)
        {
            this.dvrPassword = dvrPassword;
            this.analyse = a;

      
        }

 

//使用委托传递的方法

private void RealCallback(short[] tempBuffer,int dvrCameraId )

{

         if (analyse != null)
         {
               analyse(tempBuffer, dvrCameraId);

          }

}

 

       }

}

 

B写好的方法为VolumeAnalysize.cs中的AudioVolume()

 

则传递方法时

................

 

 

  SoundDecodeProcesserdecoder = new SoundDecodeProcesser( channel.dvrPassword,
                      new VolumeAnalysize(channel.id, SoundWarningProcesser.ProcessVolume, getSoundVolume(channel.id), soundPercent).AudioVolume );

 

................

posted on 2010-06-11 10:00  学中医的程序员  阅读(188)  评论(0编辑  收藏  举报

导航