关于Delegate与接口回调的例子

在C#中用Delegate和接口的回调都能实现外部方法的委托调用,它们有什么区别呢?

Delegate可以用+=或-=快速的绑定或解绑多个方法。而接口实现起来则显得更麻烦。

如果Delegate只绑定一个事件,接口中也只定义了一个方法则两者是等价的。

Delegate例子:

namespace Test
{
     class Program
    {
         static  void Main( string[] args)
        {
            CarDelegate car =  new CarDelegate();
            car.ColorEvent +=  new CarDelegate.ColorHandler(ColorMethod1);
            car.ColorEvent +=  new CarDelegate.ColorHandler(ColorMethod2);
            car.Color =  " Black "; // 修改Color时会触发事件

            Console.ReadLine();
        }

         static  void ColorMethod1( string color)
        {
            Console.WriteLine( " method1= " + color);
        }

         static  void ColorMethod2( string color)
        {
            Console.WriteLine( " method2= " + color);
        }
    }

     public  class CarDelegate
    {
         private  string color;
         public  delegate  void ColorHandler( string color);
         public  event ColorHandler ColorEvent;

         public  string Color
        {
             get {  return color; }
             set
            {
                color = value;
                ColorEvent( this.color);
            }
        }
    }
}

 关于接口回调的例子:

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

namespace Test
{
     class Program
    {
         static  void Main( string[] args)
        {
            Car car =  new Car( new CarActionImpl());
            car.Color =  " Black ";

            Console.ReadLine();
        }
    }

     public  interface ICarAction
    {
         void ChangeColor( string color);
    }

     public  class CarActionImpl : ICarAction
    {
         public  void ChangeColor( string color)
        {
            Console.WriteLine( " method1= " + color);
        }
    }

     public  class Car
    {
         private  string color;
         private ICarAction carAction;
         public Car(ICarAction carAction)
        {
             this.carAction = carAction;
        }
         public  string Color
        {
             get {  return color; }
             set
            {
                color = value;
                carAction.ChangeColor( this.color);
            }
        }
    }
}

 

你可能感兴趣的:(delegate)