■ 接口
接口只具有抽象方法和屬性。同時,接口不提供實現。也就是說,不能直接實例化接口,必須通過後文敘述的Object Expression,用類來實現接口。
接口的書寫方法如下所示。
- 接口
- type 接口名 = interface
聲明繼承
成員定義
end
interface與end在#light語句中可以省略。
下例中將抽象方法一節中的介紹中創建的抽象方法改變成接口。
接口的例子
type AnimalInterface = interface
abstract Bark : unit -> unit
end;;
|
下例中使用接口將上一節抽象方法中的代碼進行改寫。
使用接口的例子
type Dog = class
new () = {}
interface AnimalInterface with
member x.Bark () = System.Console.WriteLine("wan wan")
end
end;;
type Cat = class
new () = {}
interface AnimalInterface witme
member x.Bark () = System.Console.WriteLine("nya- nya-")
end
end;;
//let a = new Dog() in a.Bark();;
let a = new Dog() in (a :> AnimalInterface).Bark();;
let b = new Cat() in (b :> AnimalInterface).Bark();;
|
接口的實現如下文所示
- 接口的實現
- interface 接口名 with
值或成員的定義
end
稍嫌麻煩的是,不能寫成象上例中註釋掉的部分那樣的寫法.如果想不轉換類型而可以完成上述功能的話,必須要寫成下面這樣。
使用接口的例子之2
type AnimalInterface = interface
abstract Bark : unit -> unit
end;;
type Dog = class
new () = {}
interface AnimalInterface with
member x.Bark () = System.Console.WriteLine("wan wan")
end
member x.Bark () = System.Console.WriteLine("wan wan")
end;;
type Cat = class
new () = {}
interface AnimalInterface with
member x.Bark () = System.Console.WriteLine("nya- nya-")
end
member x.Bark () = System.Console.WriteLine("nya- nya-")
end;;
let a = new Dog() in a.Bark();;
let b = new Cat() in b.Bark();;
|
但是,這樣的話同樣內容的函數需要寫兩遍,就失去了接口的意義了。還有,接口內的函數與類內的函數也分開來執行了,
■ 接口的繼承
接口可以繼承接口。繼承接口時使用inherit關鍵字。
接口的繼承
type IA = interface abstract One : int -> int end;;
type IB = interface abstract Two : int -> int end;;
type IC = interface
inherit IA
inherit IB
abstract Three : int -> int
end;;
|
一個接口可以繼承多個接口。上例中IC繼承IA和IB,帶有One,Two,Three三個抽象方法。在下例中將這三個方法作爲函數進行實現。
繼承後的接口的利用
type ClassWithIC = class
new () = {}
interface IC with
member x.One n = 1
member x.Two n = 2
member x.Three n = 3
end
end;;
|
象這樣,也可以象利用普通接口那樣利用繼承後創建的接口。