2012-04-10 16 views
6

Quiero crear mi propio tipo de colección personalizada.Heredar de Seq

defino mi colección como:

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

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

Pero esto no compila No implementation was given for 'Collections.IEnumerable.GetEnumerator()

¿Cómo puedo hacer esto?

+6

Es necesario 'IEnumerable', así como' 'IEnumerable

Respuesta

12

En F # seq es realmente solo un alias para System.Collections.Generic.IEnumerable<T>. El genérico IEnumerable<T> también implementa el IEnumerable no genérico y, por lo tanto, su tipo F # también lo debe hacer.

La forma más fácil es simplemente tener el no genérica una llamada en el genérica uno

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

usted podría ahorrar unos pocos caracteres con' esto. Collection.GetEnumerator() |> upcast' –

+0

@JoelMueller Nunca antes había visto el operador upcast. Mucho más bonito. ¡Gracias! – JaredPar

+6

@JoelMueller: Aún más corto: 'x.Collection.GetEnumerator():> _' – Daniel