继承自Seq

Pau*_*icz 6 f#

我想创建自己的自定义集合类型.

我将我的收藏定义为:

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

   interface seq<string> with
      member this.GetEnumerator() = this.Collection.GetEnumerator()
Run Code Online (Sandbox Code Playgroud)

但这不编译 No implementation was given for 'Collections.IEnumerable.GetEnumerator()

我该怎么做呢?

Jar*_*Par 13

在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()
Run Code Online (Sandbox Code Playgroud)

  • @JoelMueller:更短:`x.Collection.GetEnumerator():> _` (6认同)
  • 你可以使用`this.Collection.GetEnumerator()|> upcast`保存一些字符 (3认同)
  • 它也可以用于类型,所以把它想象成一个'匿名'而不是'忽略'的功能,你会更接近.例如,在d.Add("one",1)`的`let d = Dictionary <_,_>()中,`d`将被推断为`Dictionary <string,int>`. (2认同)
  • sample应为'this.Collection.GetEnumerator():> _'或'upcast this.Collection.GetEnumerator()' (2认同)