欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 编程语言 > c# >内容正文

c#

c#——《c#语言程序设计》实验报告——继承与多态——电视和电灯委托 -凯发k8官方网

发布时间:2024/10/5 c# 38 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 c#——《c#语言程序设计》实验报告——继承与多态——电视和电灯委托 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
  • 掌握c#中各种成员的写法;
  • 掌握c#继承和多态概念;
  • 掌握常用接口的使用方法。
  • 运用委托知识,完成以下程序:
  • 有下面两个类,代表电视和电灯,设计两个委托,在program类的main函数中,同时打开电视和电灯,再同时关闭它们。

    class tv{public void on(int channel){console.writeline("电视已打开,在看" channel "频道");}public void off(){console.writeline("电视已关闭");}}class lights{static bool[] light = new bool[5];public static void turnon(int no){if (no >= 1 && no <= 5){light[no - 1] = true;console.writeline("已经开了" no "号灯");}}public static void turnoff(){for (int i = 0; i < 5; i )light[i] = false;console.writeline("电灯已全部关闭");}}

    源代码

    using system;namespace homework16 {class tv{public void on(int channel){console.writeline("电视已打开,在看" channel "频道");}public void off(){console.writeline("电视已关闭");}}class lights{static bool[] light = new bool[5];public static void turnon(int no){if (no >= 1 && no <= 5){light[no - 1] = true;console.writeline("已经开了" no "号灯");}}public static void turnoff(){for (int i = 0; i < 5; i )light[i] = false;console.writeline("电灯已全部关闭");}}public class controller{//定义字段private tv tv;private lights lights;//构造函数public controller() { }//定义委托类型startmachine ,返回值为void。//所以要求委托指向的方法返回值也为空//delegate关键字相当于类类型的class关键字public delegate void startmachine(int number);//声明一个stopmmachine类型的对象public startmachine startmachine;//添加委托//定义委托类型stopmachine ,返回值为void, stopmachine()的参数列表为空。//所以要求委托指向的方法返回值也为空,参数列表也为空。//delegate关键字相当于类类型的class关键字public delegate void stopmachine();//声明一个stopmmachine类型的对象public stopmachine stopmachine;//添加委托public void add(startmachine startmethod,stopmachine stopmethod){ //实例化对象this.startmachine = startmethod;this.stopmachine = stopmethod;//相当于//stopmachine = new stopmachine(tv.shuttv);//stopmachine = new stopmachine(computer.shutcomputer);//stopmachine = new stopmachine(light.shutlight);}//删除委托public void remove(startmachine startmethod,stopmachine stopmethod){this.stopmachine -= stopmethod;this.startmachine -= startmethod;}//调用委托public void open(int number){startmachine(number);}//调用委托public void shut(){stopmachine();}}class program{static void main(string[] args){//实例化类controller controller = new controller();tv tv = new tv();lights light = new lights();//添加委托controller.add(tv.on,tv.off);controller.add(lights.turnon, lights.turnoff);//调用委托random random = new random();controller.open(random.next(1,5));controller.shut();console.readkey();}} }

    运行结果

  • 掌握c#中各种成员的写法;
  • 掌握c#继承和多态概念;
  • 掌握常用接口的使用方法。
  • https://www.cnblogs.com/zcttxs/archive/2012/06/24/2560154.html

    https://shentuzhigang.blog.csdn.net/article/details/105022881

    https://www.cnblogs.com/jeffrey-chou/p/11907530.html

    总结

    以上是凯发k8官方网为你收集整理的c#——《c#语言程序设计》实验报告——继承与多态——电视和电灯委托的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

    网站地图