2015年11月18日 星期三

C14_6_2 委派中的協變和逆變

using System;
///
///定義基底類別
///
public abstract class Goods
{ }
///
///延伸一個牛奶類別
///
public class Milk : Goods
{
    //定義一個委派
    private delegate void DeliveryMilkEventHandler(Milk milk);
    //送牛奶事件
    private event DeliveryMilkEventHandler deliveryMilk;
    public void OnDeliveryMilk(Milk m)
    {
        //訂閱事件處理程式
        this.deliveryMilk += new DeliveryMilkEventHandler(Warehouse.Delivery);
        this.deliveryMilk(m);
    }
}
///
///延伸一個報紙類別
///
public class Newspaper : Goods
{
    //定義一個委派
    private delegate void DeliveryNewspaperEventHandler(Newspaper newspaper);
    //送報紙
    private event DeliveryNewspaperEventHandler deliveryNewspaper;
    public void OnDeliverNewspaper(Newspaper n)
    {
        //訂閱事件處理程式
        this.deliveryNewspaper += new DeliveryNewspaperEventHandler(Warehouse.Delivery);
        this.deliveryNewspaper(n);
    }
}
///
///倉庫
///
public static class Warehouse
{
    /*建立Goods型別參數的事件處理程式,其中,Milk 和 Newspaper 型形可以隱式的轉換成Goods型別*/
    public static void Delivery(Goods goods)
    {
        Console.WriteLine("送貨方法");
    }
}
public class Program
{
    public static void Main()
    {

    }
}

沒有留言: