我正在考慮使用抽象類與所有抽象成員,而不是一個接口,以避免顯式接口實現鍋爐代碼。因此,而不是不使用抽象類而不使用接口的原因?
type IMyInterface =
abstract Name : string
abstract Text : string
type MyClass() =
member __.Name = "name"
member __.Text = "text"
interface IMyInterface with
member this.Name = this.Name
member this.Text = this.Text
我不得不
[<AbstractClass>]
type MyAbstractClass() =
abstract Name : string
abstract Text : string
type MyClass() =
inherit MyAbstractClass()
override __.Name = "name"
override __.Text = "text"
慎用或影響的任何話,我應該知道的嗎?
如果你在一個接口和一個抽象基類之間作出決定,你也可以考慮使用兩者。提供一個抽象基類型,實現者可以*選擇*繼承,並讓它實現一個接口。然後,接受對接口的引用,而不是ABC。這在每種情況下都不起作用(例如,您的代碼實際上需要ABC中的代碼存在於每個具體實現中,並且不能接受備用實現),但通常可能是一個好主意。 – 2011-04-24 05:04:41
@Merlyn Morgan-Graham - 絕佳的建議!我正在嘗試這種方法,迄今爲止它工作得很好,給了兩全其美。 – 2011-04-24 15:54:47