|
楼主 |
发表于 2013-10-31 00:06:28
|
显示全部楼层
代码段一:使用委托和事件
[code=csharp]namespace shaoshui
{
public class heat
{
public delegate void boil(int temp);
public event boil heater;
private int wendu=0;
public void boilwater()
{
for (int i = 0; i <= 100; i++)
{
wendu = i;
if (wendu > 95)
{
if (heater != null)
{
heater(wendu);
}
}
}
}
}
public class show
{
public void show1(int temp)
{
Console.WriteLine("水开了!快{0}度了",temp);
}
}
public class display
{
public static void display1(int temp)
{
Console.WriteLine("嘀嘀嘀!已经{0}度了", temp);
}
}
class Program
{
static void Main(string[] args)
{
heat heat1 = new heat();
show show1 = new show();
heat1.heater += show1.show1;
heat1.heater += display.display1;
heat1.boilwater();
Console.ReadKey();
}
}
}
代码段二仅使用委托
[/code][code=csharp]namespace 委托6
{
public delegate void boil(int temp);
public class heat
{
//public delegate void boil(int temp);
//public event boil heater;
private int wendu;
public boil heater;
public void boilwater()
{
for (int i = 0; i <= 100; i++)
{
wendu = i;
if (wendu > 95)
{
if (heater != null)
{
heater(wendu);
}
}
}
}
}
public class show
{
public void show1(int temp)
{
Console.WriteLine("水快开了!快{0}度了",temp);
}
}
public class display
{
public static void display1(int temp)
{
Console.WriteLine("嘀嘀嘀!已经{0}度了", temp);
}
}
class Program
{
static void Main(string[] args)
{
heat heat1 = new heat();
show show1 = new show();
heat1.heater = show1.show1;//为委托绑定方法
heat1.heater += display.display1;
heat1.boilwater();//等价于为方法附上实参
Console.ReadKey();
}
}
}
[/code]
|
|