2014-10-10 35 views
7

考慮這個接口:當用作通用接口參數時,爲什麼`unit`被F#類型系統區別對待?

type A<'a> = 
    abstract X : 'a 

讓我們試着去實現它與int作爲一般的說法:

{ new A<int> with member this.X = 5 } // all is well 

現在,讓我們試着unit一個說法:

// Compiler error: The member 'get_X : unit -> unit' does not have the correct type to override the corresponding abstract method. 
{ new A<unit> with member this.X =() } 

現在,如果我們定義一個非通用接口,一切也都很好:

type A_int = 
    abstract X : int 

{ new A_int with member this.X = 5 } // works 

type A_unit = 
    abstract X : unit 

{ new A_unit with member this.X =() } // works as well! 

有什麼我可以解決這個問題嗎?

+0

在C#中不可能有一個返回'void'的泛型函數 - 例如參見https://programmers.stackexchange.com/questions/131036/why-is-void-not-allowed-as-a- generic-type-in​​-c。在這種情況下,類似的限制可能被應用於F#代碼。 – 2014-10-10 11:40:59

回答

5

在F#中,聲明返回類型爲unit的抽象插槽在.NET IL中編譯爲返回類型void。相反,聲明返回類型爲「T」的抽象槽在.NET IL中被編譯爲通用返回類型「T」,當T被unit實例化時,該變量變爲unit'

請參見:F# interface inheritance failure due to unit

0

你一般成員X可以是任何類型的值。 F#中的'unit'並不是真正的類型(如果你願意的話,它可能是非常特殊的類型) - 這是沒有任何價值的。

相關問題