2013-11-22 118 views
0

所以我一直在研究F#上的接口。我找到了這兩篇文章。 MSDNF# for fun and profit但不幸的是,他們只是皮膚深。F#如何在單獨的模塊中使用接口

修訂

這裏是我與我的接口模塊

//open statements omitted for brevity 

module DrawingInterfaces = 

    ///gets a string representation of the SVG code representation of the object 
    type IRepresentable_SVG = 
     abstract member getSVGRepresenation : unit -> string 

//other interfaces omitted for brevity 

現在相同的命名空間和物理文件夾也中我有這樣的:

type lineSet (x1off,x2off,y1off,y2off,x1,x2,y1,y2,rot,rotOff,count) = 

    //tons of member vals omitted for brevity 

    member val x1Start = x1 with get, set 

    interface DrawingInterfaces.IRepresentable_SVG with 
      member __.getSVGRepresenation() = 

       let mutable svg = "" 
       let mutable currentx1 = x1Start 
       svg 

這曾經給我2錯誤,在我使用__之前。爲會員提供符號。第一個錯誤是在接口線上。還有一條是成員線。 錯誤分別爲:

The type 'IRepresentable_SVG' is not defined 


This instance member needs a parameter to represent the object being invoked. 

我能夠通過更改文件順序來修復第一個錯誤。感謝John Palmer。 第二個幾乎是固定的。/

使用__後。符號我能夠擺脫第二個錯誤。但是,當我嘗試在接口實現中使用類型成員時,現在會彈出一個新錯誤。

 let mutable currentx1 = x1Start 

x1Start顯示爲未定義。我需要能夠在我的實現中使用存儲在其他成員中的值。

+3

F#對文件編譯順序很敏感。定義文件是否在Visual Studio中的用法文件之上? –

+0

更改編譯順序解決了第一個問題。 –

回答

3

讓我們先讓它工作,然後指出你的問題。我定義下面2個獨立的模塊,2個獨立的.fs文件相同的命名空間Example內,用於在模塊Example.UseInterface接口定義在模塊Example.DrawingInterfaces和接口實施並且也是控制檯應用程序,將使用從第三(implicit)模塊的接口Program。在我的項目對應的代碼文件是按以下順序:DefInterface.fsUseInterface,fsProgram.fs(我也做了一些慣用的造型變化和更簡潔遺漏)

文件:DefInterface.fs

namespace Example 
module DrawingInterfaces = 
    type IRepresentable_SVG = 
     abstract member GetSVGRepresenation : unit -> string 

文件:UseInterface.fs

namespace Example 
module UseInterface = 
    type LineSet (x1) = 
     member val X1Start = x1 with get, set 
     interface DrawingInterfaces.IRepresentable_SVG with 
      member __.GetSVGRepresenation() = "test" + " " + __.X1Start.ToString() 

文件:Program.fs

open Example 
open System 

[<EntryPoint>] 
let main argv = 
    let lineSet = UseInterface.LineSet(5) 
    let example : DrawingInterfaces.IRepresentable_SVG = lineSet :> _ 
    example.GetSVGRepresenation() |> printfn "%A" 
    lineSet.X1Start <- 10 
    example.GetSVGRepresenation() |> printfn "%A" 
    0 

編譯,運行並確保其正常工作。

我們代碼中的問題:

  • 第一個錯誤信息是由於需要參照完整實現的接口名UseInterface.fs,這是Example.DrawingInterfaces.IRepresentable_SVG莖雖然爲兩個模塊都屬於同一個命名空間Example前綴可省略
  • 第二個錯誤消息指向需要使用實例實現類中的方法UseInterface.LineSet,這是通過預先確定self-identifier__.方法簽名

最後,請注意Program.fs一個導入的命名空間的界面的使用,分別定義和實施提供了模塊名稱,也明確地把實現LineSetIRepresentable_SVG

編輯:我添加X1Start財產原LineSet,以顯示它如何從每題筆者的請求接口實現中使用。現在自我編號__.是更多的參與,並可能使用self.甚至this.而不是更有意義。

+0

有趣的選擇自我標識:) – Jwosty

+0

我來自Java和最近的C#背景。我發現很難關聯或理解這個自我標識符概念。你能否解釋一下,或者將我指向一篇文章呢?從我的背景中,方法名稱只是一個方法名稱。在C#或Java實現接口方法非常簡單。我假設,F#接口和自我標識符的學習曲線增加了一定程度的靈活性。 –

+0

在SO上有非常好的[自我標識問答](http://stackoverflow.com/questions/5355334/what-are-the-benefits-of-such-flexible-self-identifiers-in-f)有非常深思熟慮的評論。此外,它指出,當使用self-id'__。'是有道理的。 –

相關問題