2011-04-29 17 views
2

爲什麼這個F#類不編譯(與VS2010):與用於F#類tupled參數的默認方法

type Base = 
    abstract func : (int * int) -> int 

    default this.func (x : int, y : int) : int = 
     x + y 

FUNC的默認實現導致此編譯錯誤:

Error 9 This override takes a different number of arguments to the corresponding abstract member 

如果我改變它是一個成員:

type Base = 
    abstract func : (int * int) -> int 

    member this.func (x : int, y : int) : int = 
     x + y 

然後編譯(雖然我相信現在抽象的func沒有實現),第二個func的類型與第一個匹配。

在相關說明中,爲什麼編譯器不要求Base的第二個定義具有AbstractClass屬性?

+0

你問:「爲什麼**不**編譯器需要第二定義有一個AbstractClass屬性?「 - 當我測試這個時,編譯器**確實需要這個屬性。你使用的是什麼版本的編譯器? – wmeyer 2011-04-29 16:02:26

+0

@wmeyer:你說得對。由於我測試上述代碼的文件有進一步的錯誤,因此intellisense沒有突出顯示缺少AbstractClass屬性作爲錯誤。 – 2011-04-29 16:13:30

回答

5

剛剛擺脫了括號:

type Base = 
    abstract func : int * int -> int 

    default this.func (x : int, y : int) : int = 
     x + y 

你甚至可以縮短一點:

default this.func(x, y) = x + y 
4

爲了得到第一個版本的編譯,你需要寫:

type Base1 = 
    abstract func : (int * int) -> int 
    default this.func((x : int, y : int)) : int = 
     x + y 

我沒有鏈接到規範,但F#一般不會編譯成員稱取元組作爲參數的方法。它通常使用帶有多個參數的.NET/C#友好方法。 abstract成員強制執行此表示,因此default成員需要使用更明確的語法來執行相同的操作。

你在理解第二種類型時是正確的 - 第二種聲明是一個抽象類,它具有未實現的抽象方法(以及另一個碰巧具有相同名稱的方法)。爲此,F#需要AbstractClass屬性(它不需要用於上述內容,因爲它不是抽象的)。

+0

謝謝。雖然你的答案在技術上是正確的(而且更具信息性),但我選擇了丹尼爾的答案,因爲他發現我不需要括號)。我傾向於在F#,C#和C++之間進行混淆。 – 2011-04-29 16:12:00