2012-04-10 85 views
6

我想創建自己的自定義集合類型。繼承自Seq

我定義我的集合爲:

type A(collection : seq<string>) = 
    member this.Collection with get() = collection 

    interface seq<string> with 
     member this.GetEnumerator() = this.Collection.GetEnumerator() 

但是,這並不編譯No implementation was given for 'Collections.IEnumerable.GetEnumerator()

我如何做到這一點?

+6

您需要'IEnumerable'以及'IEnumerable的' – 2012-04-10 21:30:32

回答

12

在F#seq實際上只是System.Collections.Generic.IEnumerable<T>的別名。通用IEnumerable<T>也實現了非泛型IEnumerable,因此您的F#類型也必須這樣做。

最簡單的方法是隻擁有非一般的一個呼叫到通用一個

type A(collection : seq<string>) = 
    member this.Collection with get() = collection 

    interface System.Collections.Generic.IEnumerable<string> with 
    member this.GetEnumerator() = 
     this.Collection.GetEnumerator() 

    interface System.Collections.IEnumerable with 
    member this.GetEnumerator() = 
     upcast this.Collection.GetEnumerator() 
+3

你可以節省一些用'這個字符。 Collection.GetEnumerator()|> upcast' – 2012-04-10 22:02:25

+0

@JoelMueller我真的從來沒有見過upcast算子。更好。謝謝! – JaredPar 2012-04-10 22:04:33

+6

@JoelMueller:更短:'x.Collection.GetEnumerator():> _' – Daniel 2012-04-10 22:35:58