C# delegate multicast single delegate(曹海涛)

网友投稿 785 2022-09-11

C# delegate multicast single delegate(曹海涛)

C# delegate multicast single delegate(曹海涛)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ConsoleApp386

{

class Program

{

static void Main(string[] args)

{

Thermostat thermostat = new Thermostat();

Heater heater = new Heater(60);

Cooler cooler = new Cooler(80);

Action del1;

Action del2;

Action del3;

del1 = heater.OnTemperatureChanged;

del2 = cooler.OnTemperatureChanged;

Console.WriteLine("Invoke both delegates:");

del3 = del1;

del3 += del2;

del3(90);

Console.WriteLine("Multicast delegates:");

foreach(var dl in del3.GetInvocationList())

{

Console.WriteLine($"Target:{dl.Target},Method:{dl.Method}");

}

Console.WriteLine();

Console.WriteLine("Invoke only del2:");

del3 -= del1;

del3(30);

Console.WriteLine("\nSingle delegate:");

foreach (var dl in del3.GetInvocationList())

{

Console.WriteLine($"Target:{dl.Target},Method:{dl.Method}");

}

Console.ReadLine();

}

}

class Cooler

{

public float Temperature

{

get;set;

}

public Cooler(float temperature)

{

Temperature = temperature;

}

public void OnTemperatureChanged(float newTemperature)

{

if(newTemperature>Temperature)

{

Console.WriteLine("Cooloer:On");

}

else

{

Console.WriteLine("Cooler:Off");

}

}

}

class Heater

{

public float Temperature

{

get;set;

}

public Heater(float temperature)

{

Temperature = temperature;

}

public void OnTemperatureChanged(float newTemperature)

{

if(newTemperature

{

Console.WriteLine("Heater:On");

}

else

{

Console.WriteLine("Heater:Off");

}

}

}

public class Thermostat

{

//Define the event publisher

public Action OnTemperatureChange { get; set; }

private float currentTemperatureValue;

public float CurrentTemperature

{

get

{

return currentTemperatureValue;

}

set

{

if(value!=currentTemperatureValue)

{

currentTemperatureValue = value;

OnTemperatureChange?.Invoke(value);

}

}

}

}

}

{

Console.WriteLine("Heater:On");

}

else

{

Console.WriteLine("Heater:Off");

}

}

}

public class Thermostat

{

//Define the event publisher

public Action OnTemperatureChange { get; set; }

private float currentTemperatureValue;

public float CurrentTemperature

{

get

{

return currentTemperatureValue;

}

set

{

if(value!=currentTemperatureValue)

{

currentTemperatureValue = value;

OnTemperatureChange?.Invoke(value);

}

}

}

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Cannot open include file: ‘Windows.h‘: No such file or directory
下一篇:MDT8456部署Windows10 21H2系列 (二): 基础篇—导入镜像、驱动、软件、语言包
相关文章

 发表评论

暂时没有评论,来抢沙发吧~