2011-04-07 37 views
2

難以置信的OOP接口F#問題。F#OOP - 實現接口 - 私有和方法名稱問題

示例 - 當我創建一個類並嘗試實現單個方法從命名空間運行(字符串,字符串,字符串)從接口IRunner示例 我可以在.NET Reflector中看到真正創建的是私有方法命名爲Example-IRunner-Run(字符串,字符串,字符串)如果我然後想公開這個回到C#lib它提出了一個問題。通過反射 - 我無法控制的代碼只是使用公共Run方法尋找一個類。我如何解決?似乎無法找到關於此的任何文檔。

問題1 - 運行應該是公開的一些如何結束了私人
問題2 - 瘋狂長的方法名 - 而不是隻運行

不知道如果我需要使用一些修改關鍵字或簽名文件....(1)private(2)奇怪的方法名稱(反射不會找到)

注意:在此示例中,Run返回int
在此當前實現中我只是想回到1來「概念驗證」,我可以在F#中做這個簡單的事情。#

示例代碼:

namespace MyRunnerLib 

open Example 

type MyRunner() = class 
    interface IRunner with 
    member this.Run(s1, s2, s3) = 1 
end 

回答

3

此外,有幾個選項如何寫這個。 Robert的版本在其他成員中有實際的實現。如果將實現放置到界面中,則可以避免投射。
(另請注意,你不需要class .. end關鍵字):

type MyRunner() = 
    member this.Run(a,b,c) = 1 
    interface IRunner with 
    member this.Run(a,b,c) = this.Run(a,b,c) 

稍微清晰的方法是定義的功能是以本地功能,然後就導出兩次:

type MyRunner() = 
    // Implement functionality as loal members 
    let run (a, b, c) = 1 

    // Export all functionality as interface & members 
    member this.Run(a,b,c) = run (a, b, c) 
    interface IRunner with 
    member this.Run(a,b,c) = run (a, b, c) 
1

在Euphorics答案的第一個鏈接包含了解決方案。作爲參考,我會在此重申。您需要使用您感興趣的方法在您的類上實現轉發成員。這是因爲接口在F#中顯式實現,而在C#中,默認情況下是隱式接口實現。在你的情況:

namespace MyRunnerLib 

open Example 

type MyRunner() = class 
    interface IRunner with 
    member this.Run(s1, s2, s3) = 1 
    member this.Run(s1, s2, s3) = (this :> IRunner).Run(s1,s2,s3) 
end