BOO大全/介面

维基教科书,自由的教学读本
(重定向自BOO/BooInterfaces

上一章:類別 目錄 下一章:列舉


介面[编辑]

介面與 Abstract 基底類別相似,但介面不提供任何功能實作。如果你的類別實作了一個特定介面,那麼你的類別必須要實作介面所定義的方法與屬性,這樣才能保障使用你類別的人。

interface IAnimal:
	Name as string:
		get:
			pass
		set:
			pass
	
	def Speak()
	
class Cat (IAnimal):
	[property(Name)]
	_name as string
	
	def Speak():
		print "miaow"
		
def Speaker(x as IAnimal):
	x.Speak()
	
c = Cat(Name : "Felix")
Speaker(c)

類別與介面定義的最大差別在於介面的方法與屬性只有宣告,沒有實作或只有 pass 述句。介面的回傳值必須要明確 (如果沒指定,就表示 void),因為並沒有任何 return 述句可以推導回傳型別。

實作介面的類別必須要提供介面所有屬性與方法的實作。它們不能是虛擬方法(virtual method),同時也不需要加上 override 修飾詞。

類別無法繼承超過一個以上的類別,但是可以實作許多的介面。

在 CLI 裡,介面被非常廣泛的使用。舉例來說,實作 IDisposable 的類別可以在物件被釋放時作些特定的程式。一般來說,雖然 Framework 會幫你管理記憶體的使用,但這並不表示其他的資源也會,例如開啟檔案。

重導輸出[编辑]

這是一個實作 IDisposable 介面的例子。它讓你可以將 print 的輸出轉向到檔案或任何繼承自 TextWriter 的物件。要注意,Dispose並不是一個虛擬方法,因此不需要 overrideDispose

import System
import System.IO

class RedirectOutput(IDisposable):
	_consoleWriter as TextWriter
	_out as TextWriter
	
	def constructor(outf as TextWriter):
		Init(outf)
		
	def constructor(file as string):
		Init(File.CreateText(file))
	
	def Init(outf as TextWriter):
		_consoleWriter = Console.Out
		_out = outf
		Console.SetOut(_out)

	# implement IDisposable
	def Dispose():
		Console.SetOut(_consoleWriter)
		_out.Close()

很直覺的代碼。SetOut 方法可以指定新的 TextWriterConsole,作為寫出的標的﹔我們只要記得在物件釋放時,將 TextWriter 關閉即可。

using RedirectOutput("out.tmp"):
	print "here's the first line"
	print "and the second"

sw = StringWriter()
using RedirectOutput(sw):
	print "val = ",val,"; delta = ",delta
s = sw.ToString()

搭配 using 使用,可以確保在使用完物件之後,能自動呼叫物件的 Dispose 方法。


上一章:類別 目錄 下一章:列舉