您的位置:首页 > 其它

四、集合与泛型、委托与事件-----《大话设计模式》

2015-09-16 20:42 218 查看

一、集合与泛型

数组集合(ArrayList)泛型
优点连续存储、快速从头到尾遍历和修改元素使用大小可按需动态增加类型安全;省去拆箱和装箱操作
缺点创建时必须制定数组变量的大小;
两个元素之间添加元素比较困难
类型不安全,接受所有类型的数据;
导致一直进行拆箱和装箱操作,带来很大的性能消耗
publicpartialclassForm1:Form
{
IListarrayAnimal_list=newArrayList();//声明并初始化集合
IList<Animal>arrayAnimal;//声明泛型

privatevoidbutton3_Click(objectsender,EventArgse)
{
foreach(AnimaliteminarrayAnimal_list)//遍历集合
{
MessageBox.Show(item.Shout());
}
}
privatevoidbutton7_Click(objectsender,EventArgse)
{
arrayAnimal_list.RemoveAt(1);//初始计数为0,当1号位数据被删掉后,2号位数据的计数会变为1
arrayAnimal_list.RemoveAt(1);//这样才能删除其后数据,它始终都保证元素的连续性
}

privatevoidbutton4_Click(objectsender,EventArgse)
{
arrayAnimal=newList<Animal>();//初始化泛型
arrayAnimal.Add(AnimalFactory.CreateAnimal("猫","小花",1));//其添加指定类型数据
arrayAnimal.Add(AnimalFactory.CreateAnimal("狗","阿毛",2));
MessageBox.Show(arrayAnimal.Count.ToString());//获得元素个数
}

}




二、委托与事件

委托是一种引用方法的类型,一旦为委托分配了方法,委托将与该方法具有安全相同的行为;事件是在发生其他类或对象关注的事情时,类或对象可通过事件通知它们。

个人理解是为了让一个类能在内部执行其他类的方法,与观察者模式结合会有更好的效果。

classProgram//委托和事件都在Cat类中定义,是为了由Cat类去触发Mouse类;当Cat发出叫声时,Mouse就会跑
{
staticvoidMain(string[]args)
{
Catcat=newCat("Tom");
Mousemouse1=newMouse("Jerry");
Mousemouse2=newMouse("Jack");
cat.CatShout+=newCat.CatShoutEventHandler(mouse1.Run);//这两行表示将Mouse的Run方法通过实例化委托
cat.CatShout+=newCat.CatShoutEventHandler(mouse2.Run);//Cat.CatShoutEventHandler登记到Cat的事件CatShout当中

cat.Shout();//实现猫一叫,老鼠就跑的需求

Console.Read();
}
}

//无参数委托事件
classCat
{
privatestringname;
publicCat(stringname)
{
this.name=name;
}

publicdelegatevoidCatShoutEventHandler();//声明委托CatShoutEventHandler
publiceventCatShoutEventHandlerCatShout;//声明事件CatShout,它的事件类型是委托CatShoutEventHandler

publicvoidShout()
{
Console.WriteLine("喵,我是{0}.",name);

if(CatShout!=null)
{
CatShout();//当执行Shout()方法时,如果Catshout中有对象登记事件,则执行CatShout();
}
}
}

classMouse
{
privatestringname;
publicMouse(stringname)
{
this.name=name;
}

publicvoidRun()
{
Console.WriteLine("老猫来了,{0}快跑!",name);
}
}



//有参数委托事件,增加了一个CatShoutEventArgs,用来传递Cat的名字
classCat
{
privatestringname;
publicCat(stringname)
{
this.name=name;
}

publicdelegatevoidCatShoutEventHandler(objectsender,CatShoutEventArgsargs);//声明委托时有两个参数
publiceventCatShoutEventHandlerCatShout;//sender用来指向发送通知的对象,args用来传递数据

publicvoidShout()
{
Console.WriteLine("喵,我是{0}.",name);

if(CatShout!=null)
{
CatShoutEventArgse=newCatShoutEventArgs();//实例化参数
e.Name=this.name;
CatShout(this,e);//当事件触发时,将这两个参数传递给委托
}
}
}

classMouse
{
privatestringname;
publicMouse(stringname)
{
this.name=name;
}

publicvoidRun(objectsender,CatShoutEventArgsargs)//由于委托增加了两个参数,这里也增加了两个参数
{
Console.WriteLine("老猫{0}来了,{1}快跑!",args.Name,name);
}
}


publicclassCatShoutEventArgs:EventArgs//继承EventArgs,用来传递数据

{

privatestringname;

publicstringName

{

get{returnname;}

set{name=value;}

}

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐
章节导航