F#介面由於單位繼承故障
type MyInterface<'input, 'output> = abstract member MyFun: 'input -> 'output type MyClass() = interface MyInterface<string, unit> with member this.MyFun(input: string) = () //fails with error FS0017: The member 'MyFun : string -> unit' does not have the correct type to override the corresponding abstract method. type MyUnit = MyUnit type MyClass2() = //success interface MyInterface<string, MyUnit> with member this.MyFun(input: string) = MyUnit
這在F#語言中看起來像是一個討厭的角色,但我不知道它是否符合編譯器的設計限制或錯誤.如果是設計限制,則錯誤訊息應該說(因為目前來說,這並不太有意義).
無論如何,問題是F#編譯器不會在IL中生成實際包含單元型別的程式碼.它用void(當用作返回型別)或空引數列表(用作方法或函式引數)時替換它).
這意味著在MyClass型別中,編譯器決定將MyFun成員編譯成一個接受字串並返回void(但不能使用void作為通用型別引數的方法)的方法,因此這不起作用).原則上,在這種情況下,編譯器可以使用實際的單元型別(因為這是唯一的方式來使其執行),但是這可能會在別的地方產生其他不一致.
建立MyUnit的訣竅是,我認為,解決問題是一個很好的方法.即使核心的F#庫在實現的某些地方(在非同步工作流程中)使用類似MyUnit的東西來處理單元的一些限制(以及它被編譯的方式).
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/4485445/f-interface-inheritance-failure-due-to-unit