C#实验委托事件与继承汇总.docx
- 文档编号:1954898
- 上传时间:2023-05-02
- 格式:DOCX
- 页数:29
- 大小:22.25KB
C#实验委托事件与继承汇总.docx
《C#实验委托事件与继承汇总.docx》由会员分享,可在线阅读,更多相关《C#实验委托事件与继承汇总.docx(29页珍藏版)》请在冰点文库上搜索。
C#实验委托事件与继承汇总
实验二委托、事件与继承
一、实验目的
1.掌握扩展函数的用法;
2.掌握C#委托和事件的用法;
3.掌握C#继承和多态概念;
4.掌握常用接口的使用方法。
二、实验内容
(实验过程中编写的程序复制到本文件中,下课整理后上交)
1.编写一个静态类MyExtensions,扩展.NETFramework基本类型的功能。
1)定义一个扩展方法IsPalindrome,扩展string类的功能,来判断字符串是否为回文(指顺读和倒读内容都一样的文本)。
为提高程序效率,该方法中不能直接调用Reverse方法。
2)定义一个扩展方法ReverseDigits,允许int将自己的值倒置,例如将整型1234调用ReverseDigits,返回结果为4321。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceexperiment2
{
staticclassMyExtensions
{
publicstaticboolIsPalindrome(thisstringstr)
{
for(inti=0;i { if(str[i]! =str[str.Length-1-i]) { returnfalse; } } returntrue; } publicstaticintReverseDigits(thisintnum) { intj=0,Reverse_num=0; int[]a=newint[10];//数组中元素的数量应该是可变的 for(inti=0;;i++)//注意 { if(num==0)//1? break; a[i]=num%10; j++; num/=10; } for(inti=0;i { Reverse_num+=(int)(a[i]*Math.Pow(10,j-i-1));//这儿一定要强制转换成int } returnReverse_num; } } classProgram { staticvoidMain(string[]args) { stringstr; inta; Console.Write("Enterastring: "); str=Console.ReadLine(); Console.WriteLine("\""+str+"\""+(str.IsPalindrome()? "is": "isnot")+"apalindrome"); Console.Write("Enteraninteger: "); a=int.Parse(Console.ReadLine()); Console.WriteLine("Thereverseof"+a+"is"+a.ReverseDigits()); } } } 2.应用委托和泛型集合类知识,完成以下程序。 程序框架: 源程序2: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceexperment2_2 { classDelegates { //创建委托类型 publicdelegateboolNumberPredicate(intnumber); staticvoidMain(string[]args) { int[]numbers={1,2,3,4,5,6,7,8,9,10}; //生成委托实例 NumberPredicateevenPredicate=IsEven; //利用委托变量调用IsEven Console.WriteLine("CallIsEvenusingadelegatevariable: {0}",evenPredicate (2)); //选出偶数 List //描述并输出 DisplayList("UseIsEventofilterevennumbers: ",evenNumbers);//滤过 //选出素数并输出 NumberPredicateprimePredicate=IsPrime; List DisplayList_prime("UseIsPrimetofilterevennumbers: ",Prime); } privatestaticList { List for(inti=0;i { if(predicate(intArray[i])) { numbers.Add(intArray[i]); } } returnnumbers; } privatestaticList { List for(inti=0;i { if(predicate(intArray[i])) { numbers.Add(intArray[i]); } } returnnumbers; } //偶数判断函数 privatestaticboolIsEven(intnumber) { return(number%2==0); } //判断是否素数 privatestaticboolIsPrime(intnumber) { boolflag=true; if(number<=1) returnfalse; else { for(inti=2;i { if(number%i==0) { flag=false; break; } } } returnflag; } //列表元素输出 privatestaticvoidDisplayList(stringdescription,List { Console.Write(description); foreach(intnumberinlist) { Console.Write(number+""); } Console.WriteLine(); } privatestaticvoidDisplayList_prime(stringdescription,List { Console.Write(description); foreach(intnumberinlist) { Console.Write(number+""); } Console.WriteLine(); } } } 3.模拟连锁反应事件 (1)创建C#控制台应用程序。 (2)在程序中新建一个表示太阳的类Sun,在其中定义一个事件OnRise,一个成员方法Rise,并在方法中引发事件。 参考源代码如下(太阳只有一个,所以将其定义为静态类): publicstaticclassSun{ publicstaticeventEventHandlerOnRise; publicstaticvoidRise(){ Console.WriteLine("太阳从东方升起! "); if(OnRise! =null) OnRise(null,null); } } (3)在程序中新建一个公鸡类Cock,在其中定义私有字段_name,针对Sun.OnRise事件的处理方法Sun_OnRise,事件OnSing,以及引发该事件的方法Sing;在类的构造函数中初始化字段,并将事件处理方法与事件相关联。 参考源代码如下(Sun_OnRise方法中调用了Sing方法,表示太阳升起会使公鸡打鸣): publicclassCock{ privatestring_name; publicCock(stringname){ _name=name; Sun.OnRise+=newEventHandler(Sun_OnRise); } privatevoidSun_OnRise(objectsender,EventArgse) { Console.WriteLine("公鸡{0}: ",_name); Console.WriteLine("雄鸡一声天下白! "); this.Sing(); } publiceventEventHandlerOnSing; publicvoidSing(){ Console.WriteLine("喔喔喔……"); if(OnSing! =null) OnSing(this,null); } } (4)在程序中新建一个主人类Host,在其中同样定义字段_name,起床事件OnGetup,起床方法Getup(引发起床事件),养鸡方法Foster,以及Cock.OnSing事件的处理方法c1_OnSing,并在Foster方法中与事件相关联。 参考源代码如下(c1_OnSing方法中调用了Getup方法,表示公鸡打鸣会使主人起床): publicclassHost{ privatestring_name; publicHost(stringname){_name=name;} publiceventEventHandlerOnGetup; publicvoidGetup(){ Console.WriteLine("日出而作……"); if(OnGetup! =null) OnGetup(this,null) } publicvoidFoster(Cockc1) { c1.OnSing+=newEventHandler(c1_OnSing); } privatevoidc1_OnSing(objectsender,EventArgse) { Console.WriteLine("主人{0}: ",_name); Console.WriteLine("闻鸡起舞! "); this.Getup(); } } (5)参照Cock类和Host类中的代码,新建狗类Dog和猫类Cat,在其中定义字段_owner以记录其主人对象,定义owner_OnGetup方法以处理Host.OnGetup事件(主人起床时,输出狗叫声"汪汪"和猫叫声"喵喵";)通过属性Owner封装字段_owner,并在其set访问函数中关联事件和事件处理方法。 (6)在程序主方法中依次创建鸡、主人、狗、猫对象,而后调用Sun.Rise方法,参考源代码如下: staticvoidMain(){ Cockcock1=newCock("花花"); Hosthost1=newHost("祖逖"); Host1.Foster(cock1); Dogdog1=newDog("旺财"); dog1.Owner=host1; Catcat1=newCat("咪咪"); cat1.Owner=host1;Sun.Rise(); } (7)编译运行程序,看看"太阳升起"这一事件会引发怎样的连锁反应。 源程序3: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceexperiment2_3 { // (2) publicstaticclassSun { publicstaticeventEventHandlerOnRise;//EventHandler为委托名 publicstaticvoidRise() { Console.WriteLine("太阳从东方升起! "); if(OnRise! =null) OnRise(null,null); } } //(3) publicclassCock { privatestring_name; publicCock(stringname) { _name=name; Sun.OnRise+=newEventHandler(Sun_OnRise); } privatevoidSun_OnRise(objectsender,EventArgse) { Console.WriteLine("公鸡{0}: ",_name); Console.WriteLine("雄鸡一声天下白! "); this.Sing(); } publiceventEventHandlerOnSing; publicvoidSing() { Console.WriteLine("喔喔喔……"); if(OnSing! =null) OnSing(this,null); } } //(4) publicclassHost { privatestring_name; publicHost(stringname){_name=name;} publiceventEventHandlerOnGetup; publicvoidGetup(){ Console.WriteLine("日出而作……"); if(OnGetup! =null) OnGetup(this,null); } publicvoidFoster(Cockc1) { c1.OnSing+=newEventHandler(c1_OnSing); } privatevoidc1_OnSing(objectsender,EventArgse) { Console.WriteLine("主人{0}: ",_name); Console.WriteLine("闻鸡起舞! "); this.Getup(); } } //(5.Dog) publicclassDog { privatestring_name; privateHost_owner; publicDog(stringname) { _name=name; } publicHostOwner { get{returnthis._owner;} set { this._owner=value; Owner.OnGetup+=newEventHandler(owner_OnGetup); } } privatevoidowner_OnGetup(objectsender,EventArgse) { Console.Write("狗{0}: ",_name); Console.WriteLine("汪汪"); } } //(5.Cat) publicclassCat { privatestring_name; privateHost_owner; publicCat(stringname) { _name=name; } publicHostOwner { get{returnthis._owner;} set { this._owner=value; Owner.OnGetup+=newEventHandler(owner_OnGetup); } } privatevoidowner_OnGetup(objectsender,EventArgse) { Console.Write("猫{0}: ",_name); Console.WriteLine("喵喵"); } } //(6) classProgram { staticvoidMain(string[]args) { Cockcock1=newCock("花花"); Hosthost1=newHost("祖逖"); host1.Foster(cock1); Dogdog1=newDog("旺财"); dog1.Owner=host1; Catcat1=newCat("咪咪"); cat1.Owner=host1; Sun.Rise(); } } } 4.练习接口的使用 1)Array类的Sort方法需要数组中的元素实现IComparable接口。 简单类型如int等已实现了IComparable接口,所以可以排序。 设计一个Person类,带有FirstName和LastName属性,带的Birthday属性(DateTime类型),使之实现IComparable接口,按LastName进行比较;如果LastName相同,就按FirstName进行比较。 2)如果Person对象的排序方式与上述不同,就可以自己创建一个类,实现IComparer接口,其中定义了方法Compare,它独立于要比较的类,因此需要两个参数进行比较。 写个一PersonComparer类,继承IComparer,使得能够按Birthday进行排序。 3)写一个测试类,生成如下Person数组,调用Sort方法进行两种方式的排序。 newPerson[]{ newPerson{FirstName=“Damon”,Lastname=“Hill”,Birthday=newDateTime(1990,5,1)}, newPerson{FirstName=“Niki”,Lastname=“Lauda”,Birthday=newDateTime(1995,10,4)}, newPerson{FirstName=“Ayrton”,Lastname=“Senna”,Birthday=newDateTime(1992,6,23)}, newPerson{FirstName=“Graham”,Lastname=“Hill”,Birthday=newDateTime(1994,9,15)} 源程序4: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceInterface_4 { publicclassPerson: IComparable { publicstringFirstName; publicstringLastName; publicDateTimeBirthday; publicPerson(){} publicPerson(stringFirstName,stringLastName,DateTimeBirthday) { this.FirstName=FirstName; this.LastName=LastName; this.Birthday=Birthday; } publicintCompareTo(Personp) { if(this.LastName.CompareTo(p.LastName)==0) { returnthis.FirstName.CompareTo(p.FirstName); } else returnthis.LastName.CompareTo(p.LastName); } publicoverridestringToString() { return"FirstName="+FirstName+","+"LastName="+LastName+","+"Birthday="+Birthday; } } classPersonComparer: Person,IComparer { publicPersonComparer() { this.Birthday=Birthday; } publicintCompare(Personp1,Personp2) { returnp1.Birthday.CompareTo(p
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C# 实验 委托 事件 继承 汇总
![提示](https://static.bingdoc.com/images/bang_tan.gif)