BOO大全/介面

维基教科书,自由的教学读本

上一章:类别 目录 下一章:列举


介面[编辑]

介面与 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 方法。


上一章:类别 目录 下一章:列举