2012-04-10 88 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