一个(烧水)订阅事件的小栗子。。。。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// 订阅事件,通过烧水的温度,到一定温度的时候,触发事件
/// </summary>
namespace Boilwater
{
class boilwater
{
public delegate void testDelegate(int temperature);
public event testDelegate testevent;
public int temperature=30;
public void boil()
{
while(temperature<=100)
{
temperature++;
Thread.Sleep(1000);
if (testevent != null)
{
testevent(temperature);
}
}
}
public static void Alarm1(int temperature)
{
Console.WriteLine("当前水温"+temperature+"度");
}
public static void Alarm2(int temperature)
{
Console.WriteLine("快要烧开了");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Boilwater
{
class Program
{
static void Main(string[] args)
{
boilwater b = new boilwater();
b.testevent += boilwater.Alarm1;
b.testevent += boilwater.Alarm2;
b.boil();
Console.ReadKey();
}
}
}
Action 和Func 的概念大概是本地函数的意思,就是 不用再类里面声明delegate这个类,后面会有一个小栗子
Action<int,int> 匹配 两个参数都是int的方法,没有返回值
Func<int,int,string> 匹配两个参数都是int,返回值是string的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delegateTest1
{
class Program
{
static void Main(string[] args)
{
int[] array = { 1,2,3,4,5,6 };
int value1 = caculate(array, sum);
int value2 = caculate(array, X);
Console.WriteLine(value1);
Console.WriteLine(value2);
Console.ReadKey();
}
/// <summary>
/// 对一个数组进行计算,根据委托的方法不同,返回不同值
/// </summary>
public static int caculate(int[] items, Func<int[],int> f)
{
return f(items);
}
public static int sum(int[] items)
{
return items.Sum();
}
public static int X(int[] items)
{
int temp = 1;
foreach(int i in items)
{
temp = i * temp;
}
return temp;
}
}
}