Interface定義及使用

來源:互聯網
上載者:User
介面定義以大寫字母I開頭。方法只定義其名稱,在C#中,方法預設是公有方法;用public修飾方法是不允許的,否則會出現編譯錯誤;介面可以從別的介面繼承,如果是繼承多個介面,則父介面列表用逗號間隔。
      介面可以通過類來實現,當類的基列表同時包含基類和介面時,列表中首先出現的是基類;類必須要實現其抽象方法; 
      介面使用:見代碼(轉)
      

interface使用interface使用(執行個體一)
 
using System;
namespace Dage.Interface

{
 //印表機介面
 public interface IPrint
 {
  string
returnPrintName();
 }
}
//--------------------------------------------
using
System;
using Dage.Interface;
namespace
Dage.Print
{
 //HP牌印表機類
 public class HP: IPrint
 {
  public
string returnPrintName()
  {
   return "這是HP牌印表機";
 
}
 }
}
//--------------------------------------------
using
System;
namespace Dage.Print
{
 //Eps牌印表機類
 public class Eps:
IPrint
 {
  public string returnPrintName()
  {
   return
"這是Eps牌印表機";
 
}
 }
}
//--------------------------------------------
using
System;
using Dage.Interface;
namespace Dage
{
 //列印類
 public
class Printer
 {
  public Printer()
  {}
  public string
PrintName(IPrint iPrint)
  {
   return iPrint.returnPrintName();
 
}
 }
}
//--------------------------------------------
--WinFrom中調用代碼:
private
void button1_Click(object sender, System.EventArgs e)
{
 Printer p= new
Printer();
 switch (this.comboBox1.Text)
 {
  case "HP":
  
MessageBox.Show(p.PrintName(new HP()));
   break;
  case "Eps":
  
MessageBox.Show(p.PrintName(new Eps()));
   break;
  default:
  
MessageBox.Show("沒有發現這個品牌!");
   break;
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.