本文主要是介绍声明一个接口IPlayer,包含5个接口方法:播放、停止、暂停、上一首和下一首。设计一个Windows应用程序,在该程序中定义一个MP3播放器类和一个AVI播放器类,以实现该接口,最后创建相应类的实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
从左往右,btnMP3,lblShow,btnAVI
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace WindowsFormsApplication1
{public partial class Form1 : Form{public Form1(){InitializeComponent();}IPlayer iplayer;MP3 mp3;AVI avi;interface IPlayer //接口定义{string Play(); //播放string Stop(); //停止string Pause(); //暂停string Pre(); //上一首string Next(); //下一首}public class MP3 : IPlayer{public string Play(){return "正在播放MP3歌曲!";}public string Stop(){return "停止播放MP3歌曲!";}public string Pause(){return "暂停播放MP3歌曲!";}public string Pre(){return "播放上一首MP3歌曲!";}public string Next(){return "播放下一首MP3歌曲!";}}public class AVI : IPlayer{public string Play(){return "正在播放AVI视频!";}public string Stop(){return "停止播放AVI视频!";}public string Pause(){return "暂停播放AVI视频!";}public string Pre(){return "播放上一首AVI视频!";}public string Next(){return "播放下一首AVI视频!";}}private void btnAVI_Click(object sender, EventArgs e){avi = new AVI(); //新建AVI对象iplayer = (IPlayer)avi; //将avi转化为接口}private void btnMP3_Click(object sender, EventArgs e){mp3 = new MP3(); //新建Mp3对象iplayer = (IPlayer)mp3; //将MP3转换为接口}private void button3_Click(object sender, EventArgs e)//上一首{if (mp3 is IPlayer || avi is IPlayer) //判断{lblShow.Text = "\n" + iplayer.Pre();}else{MessageBox.Show("请选择播放MP3歌曲或AVI视频!");}}private void button5_Click(object sender, EventArgs e)//停止{if (mp3 is IPlayer || avi is IPlayer) //判断类型{lblShow.Text = "\n" + iplayer.Stop();}else{MessageBox.Show("请选择播放MP3歌曲或AVI视频!");//判断是否为空}}private void button6_Click(object sender, EventArgs e)//播放{if (mp3 is IPlayer || avi is IPlayer){lblShow.Text = "\n" + iplayer.Play();}else{MessageBox.Show("请选择播放MP3歌曲或AVI视频!");}}private void button7_Click(object sender, EventArgs e)//暂停{if (mp3 is IPlayer || avi is IPlayer){lblShow.Text = "\n" + iplayer.Pause();}else{MessageBox.Show("请选择播放MP3歌曲或AVI视频!");}}private void button4_Click(object sender, EventArgs e)//下一首{if (mp3 is IPlayer || avi is IPlayer){lblShow.Text = "\n" + iplayer.Next();}else{MessageBox.Show("请选择播放MP3歌曲或AVI视频!");}}}
}
这篇关于声明一个接口IPlayer,包含5个接口方法:播放、停止、暂停、上一首和下一首。设计一个Windows应用程序,在该程序中定义一个MP3播放器类和一个AVI播放器类,以实现该接口,最后创建相应类的实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!