【C# interface接口】模拟MP3/AVI播放器
生活随笔
收集整理的這篇文章主要介紹了
【C# interface接口】模拟MP3/AVI播放器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 注意:本程序僅模擬播放器功能,點擊按鈕時只會輸出一句話,并未真正實現播放。
對接口的理解,見我的另一篇博客,里面有詳細說明:【C# interface接口】對接口的理解、接口的使用方式(最通俗的解釋)
功能
點擊“MP3”,顯示“成功選擇MP3”
點擊下方功能按鈕,顯示反饋信息
思路
聲明一個接口Iplayer,接口具有上述函數定義(播放,停止,暫停,上一首,下一首)。然后定義兩個子類MP3 AVI,繼承于接口Iplayer,同樣擁有接口定義的所有功能。
用戶選擇MP3/AVI時,將實例化的子類MP3/AVI賦值給實例化的接口iplayer,這樣就能在選擇功能(播放,停止,暫停,上一首,下一首)時,直接調用接口的函數,而不必分情況調用子類的函數。
代碼
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;namespace 第五章_接口 {public partial class Form1 : Form{public Form1(){InitializeComponent();}Iplayer iplayer;//MP3 mp3;//AVI avi;//new mp3private void button1_Click(object sender, EventArgs e){MP3 mp3 = new MP3(); //(same as) MP3 mp3; mp3 = new MP3();iplayer = (Iplayer)mp3; //cast, then assign to InterfacetextBox1.Text = "成功選擇MP3";}//new aviprivate void button2_Click(object sender, EventArgs e){AVI avi = new AVI();iplayer = (Iplayer)avi; //cast, then assign to InterfacetextBox1.Text = "成功選擇AVI";}//playprivate void button5_Click(object sender, EventArgs e){textBox1.Text = iplayer.Play();}//preprivate void button3_Click(object sender, EventArgs e){textBox1.Text = iplayer.Pre();}//stopprivate void button4_Click(object sender, EventArgs e){textBox1.Text = iplayer.Stop();}//pauseprivate void button6_Click(object sender, EventArgs e){textBox1.Text = iplayer.Pause();}//nextprivate void button7_Click(object sender, EventArgs e){textBox1.Text = iplayer.Next();}}interface Iplayer{string Play(); //播放string Stop(); //停止string Pause(); //暫停string Pre(); //上一首string Next(); //下一首}public class MP3 : Iplayer{public string Next(){return "播放下一首MP3歌曲!";}public string Pause(){return "暫停播放MP3歌曲!";}public string Play(){return "正在播放MP3歌曲!";}public string Pre(){return "播放上一首MP3歌曲!";}public string Stop(){return "停止播放MP3歌曲!";}}public class AVI : Iplayer{public string Next(){return "播放下一首AVI視頻!";}public string Pause(){return "暫停播放AVI視頻!";}public string Play(){return "正在播放AVI視頻!";}public string Pre(){return "播放上一首AVI視頻!";}public string Stop(){return "停止播放AVI視頻!";}} }總結
以上是生活随笔為你收集整理的【C# interface接口】模拟MP3/AVI播放器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【C# interface接口】对接口的
- 下一篇: 【C# 委托 Lambda表达式】一个简