集合:动态数组(ArrayList),列表(List),字典(Dictionary),队列(Queue),栈(Stack)
委托:委托是持有一个或者多个方法的对象,并且该对象可以被执行。委托也可以声明,是一种引用类型
delegate void ActCute();
既然是一种类型,则可以定义该类型的对象
ActCute actcute;
例子:
abstract public class Pet
{
public string _name;
public Pet(string name)
{
_name = name;
}
}
public class Dog : Pet
{
public Dog(string Name) : base(Name)
{
}
public void WagTail()
{
Console.WriteLine(_name+"wag tail");
}
}
public class Cat: Pet
{
public Cat(string Name) : base(Name)
{
}
public void InnocentLook()
{
Console.WriteLine(_name + "InnocentLook");
}
}
class program
{
delegate void ActCute();//主函数外声明委托
public static void Main(string[] args)
{
Dog dog = new Dog("A");
Cat cat = new Cat("B");
ActCute del = null;
del = dog.WagTail;
del += cat.InnocentLook;//给委托添加方法
del();
Console.ReadKey();
}
}
Lambda表达式:
匿名方法:
delegate void ActCute();
ActCute del;
del=delegate(){...};//声明匿名方法
即del=()=>{...};
例:
class program
{
delegate void ActCute();
public static void Main(string[] args)
{
Dog dog = new Dog("A");
Cat cat = new Cat("B");
ActCute del = null;
del = dog.WagTail;
del += cat.InnocentLook;
del += () =>
{
Console.WriteLine("do nothing");
};//添加匿名方法
del();
Console.ReadKey();
}
}
事件:
发布者和订阅者:通知某件事情发生的是发布者。对某件事情关注的就是订阅者。
触发和注册:事件发生时,通知所有关注该事件的订阅者。想在事件发生时被通知,订阅者必须注册以表示关注。
用程序语言解释:时间发生时,通知订阅者即调用订阅者的注册函数。注册,就是告诉发布者调用哪一个注册函数。
例:
abstract public class Pet
{
public string _name;
public Pet(string name)
{
_name = name;
}
}
public class Dog : Pet
{
public delegate void Handler();//声明委托。
public static event Handler NewDog;//声明事件
public Dog(string Name) : base(Name)//触发条件即事件发生,即触发条件是new了一条新狗
{
if (NewDog != null)
{
NewDog();
}
}
}
class Client//订阅者
{
public void WantDog()
{
Console.WriteLine("Buy a dog");
}
}
class program
{
public static void Main(string[] args)
{
Client c1 = new Client();//创建订阅者
Client c2 = new Client();
Dog.NewDog += c1.WantDog;//订阅,订阅者告诉触发者,当事件发生时要触发自己的哪个方法
Dog.NewDog += c2.WantDog;
Dog dog = new Dog("A");//new 出新狗,触发NewDog()中的方法
Console.ReadKey();
}
}
事件即先声明委托,然后声明事件。创建订阅者和订阅者的方法,创建触发事件。将订阅者想在事件触发时所执行的方法委托给事件。最后当事件发生时,所有订阅者注册的方法都被执行。