有下面两个类,代表电视和电灯。定义委托类型,生成委托实例,在Program类的Main函数中,同时打开电视和电灯,再同时关闭它们。
class TV
{
public void on(int channel)
{
Console.WriteLine(“电视已打开,在看” + channel + “频道”);
}
public void off()
{
Console.WriteLine(“电视已关闭”);
}
}
class LEDLight
{
static bool[] light = new bool[5];
public static void turnon(int no)
{
if(no >= 1 && no <= 5)
{
light[no-1] = true;
Console.WriteLine(“已经开了” + no + “号灯”);
}
}
public static void turnoff()
{
for(int i=0; i<5; i++)
light[i] = false;
Console.WriteLine(“电灯已全部关闭”);
}
}
using System;
namespace consoleReview
{
class TV
{
public void on(int channel)
{
Console.WriteLine("电视已打开,在看" + channel + "频道");
}
public void off()
{
Console.WriteLine("电视已关闭");
}
}
class LEDLight
{
static bool[] light = new bool[5];
public static void turnon(int no)
{
if (no >= 1 && no <= 5)
{
light[no - 1] = true;
Console.WriteLine("已经开了" + no + "号灯");
}
}
public static void turnoff()
{
for (int i = 0; i < 5; i++)
light[i] = false;
Console.WriteLine("电灯已全部关闭");
}
}
class Program
{
delegate void OnApplaction(int no); //委托开启
delegate void OffApplaction(); //委托关闭
public static void Main()
{
TV tv = new TV();
OnApplaction on = new OnApplaction(tv.on); //传入相应方法
on += LEDLight.turnon;
on(5);//调用
OffApplaction off = tv.off;
off += LEDLight.turnoff;
off();
}
}
}