1)匿名函数分别于委托、事件的关系
1)普通匿名函数
1.针对委托的使用
2.可以快捷的使委托实例化。 3.不建议再使用匿名函数,C#3.0后使用lambda表达式替代匿名函数
匿名函数的写法
:
class Program
{
delegate int MyDelegate(int a, int b);
static void Main(string[] args)
{
MyDelegate md = delegate(int a, int b) { return a + b; };
int sum = md(1,2);
Console.WriteLine(sum);
}
}
2)事件与普通匿名函数
nternal class Program
{
static void Main(string[] args)
{
Heater heater = new Heater();
heater.BoilEvent += delegate (int x) //添加匿名函数
{
Console.WriteLine("水已经{0}度了,可以用茶杯接水了", x);
};
heater.BoilEvent += delegate (int x) //添加匿名函数
{
Console.WriteLine("水已经{0}度了,可以用大桶接水了", x);
};
heater.BoilWater();//执行事件
}
}
public class Heater
{
private int temperature;//水温
public delegate void BoilHandle(int x);//声明关于事件的委托
public event BoilHandle BoilEvent;//声明水要烧开的事件
public void BoilWater()
{ //烧水的方法
for (int i = 0; i <= 100; i++)
{
temperature = i;
if (temperature > 96)
{
if (BoilEvent != null)
{
BoilEvent(temperature);
}
}
}
}
}
3)lambda表达式(普通函数的升级版)
nternal class Program
{
static void Main(string[] args)
{
Heater heater = new Heater();
heater.BoilEvent += delegate (int x) //添加匿名函数
{
Console.WriteLine("水已经{0}度了,可以用茶杯接水了", x);
};
heater.BoilEvent += delegate (int x) //添加匿名函数
{
Console.WriteLine("水已经{0}度了,可以用大桶接水了", x);
};
heater.BoilWater();//执行事件
}
}
public class Heater
{
private int temperature;//水温
public delegate void BoilHandle(int x);//声明关于事件的委托
public event BoilHandle BoilEvent;//声明水要烧开的事件
public void BoilWater()
{ //烧水的方法
for (int i = 0; i <= 100; i++)
{
temperature = i;
if (temperature > 96)
{
if (BoilEvent != null)
{
BoilEvent(temperature);
}
}
}
}
}
4)事件与lambda表达式
internal class Program
{
static void Main(string[] args)
{
Heater heater = new Heater();
heater.BoilEvent += x =>
{
Console.WriteLine("水已经{0}度了,可以用茶杯接水了", x);
};
heater.BoilEvent += x=> //添加匿名函数
{
Console.WriteLine("水已经{0}度了,可以用大桶接水了", x);
};
heater.BoilWater();//执行事件
Console.ReadKey();
}
}
public class Heater
{
private int temperature;//水温
public delegate void BoilHandle(int x);//声明关于事件的委托
public event BoilHandle BoilEvent;//声明水要烧开的事件
public void BoilWater()
{ //烧水的方法
for (int i = 0; i <= 100; i++)
{
temperature = i;
if (temperature > 96)
{
if (BoilEvent != null)
{
BoilEvent(temperature);
}
}
}
}
}