2012-04-10 43 views
6

Tôi muốn tạo loại bộ sưu tập tùy chỉnh của riêng mình.Thừa kế từ Seq

tôi xác định bộ sưu tập của tôi như:

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

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

Nhưng điều này không biên dịch No implementation was given for 'Collections.IEnumerable.GetEnumerator()

Làm thế nào để tôi làm điều này?

+6

Bạn cần 'IEnumerable' cũng như' IEnumerable ' –

Trả lời

12

Trong F # seq thực sự chỉ là bí danh cho System.Collections.Generic.IEnumerable<T>. Các chung IEnumerable<T> cũng thực hiện không chung chung IEnumerable và do đó loại F # của bạn phải làm như vậy là tốt.

Cách đơn giản nhất là chỉ cần có không chung một cuộc gọi vào chung một

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

Bạn có thể tiết kiệm một vài ký tự với 'này. Collection.GetEnumerator() |> upcast' –

+0

@JoelMueller Tôi thực sự chưa từng thấy nhà điều hành upcast trước đây. Đẹp hơn nhiều. Cảm ơn! – JaredPar

+6

@JoelMueller: Thậm chí ngắn hơn: 'x.Collection.GetEnumerator():> _' – Daniel