在F#中实现IList <t> </t>

时间:2014-01-10 17:11:24

标签: collections f# ienumerator

我看过SO和互联网,但仍然无法弄清楚我缺少什么,以及如何在F#中实现通用的IList接口:

type OrCondition() as self =
    inherit Condition()
    member val Conditions: List<Condition> = new List<Condition>() with get, set
    interface IList<Condition> with
        member this.Item 
            with get(index) = self.Conditions.[index]
            and  set(index)(value) = self.Conditions.[index] <- value
        member this.IndexOf item = self.Conditions.IndexOf(item)
        member this.Insert(index, item) = self.Conditions.Insert(index, item)
        member this.RemoveAt(index) = self.Conditions.RemoveAt(index)
        member this.Count with get() = self.Conditions.Count
        member this.IsReadOnly with get() = false
        member this.Add(item) = self.Conditions.Add(item)
        member this.Clear() = self.Conditions.Clear()
        member this.Contains(item) = self.Conditions.Contains(item)
        member this.CopyTo(conditions, index) = self.Conditions.CopyTo(conditions, index)
        member this.Remove(item) = self.Conditions.Remove(item)
        member this.GetEnumerator() = (Seq.cast<Condition> self.Conditions).GetEnumerator()

现在编译器抱怨我没有实现Collections.IEnumerable.GetEnumerator()并且我知道它,但我真的不知道该怎么做。

更新:下面的最终结果。非常感谢加兰先生。另外,值得指出的是,我只引用了System.Collections.Generic,并且在非通用版本的IEnumerable驻留时忘记引用System.Collection。令人伤心的ReSharper不支持F#。

open System.Collections
open System.Collections.Generic

type OrCondition() as self =
    inherit Condition()
    member val Conditions = new List<Condition>() with get, set
    interface IList<Condition> with
        member this.Item 
            with get(index) = self.Conditions.[index]
            and  set(index)(value) = self.Conditions.[index] <- value
        member this.IndexOf item = self.Conditions.IndexOf(item)
        member this.Insert(index, item) = self.Conditions.Insert(index, item)
        member this.RemoveAt(index) = self.Conditions.RemoveAt(index)
        member this.Count with get() = self.Conditions.Count
        member this.IsReadOnly with get() = false
        member this.Add(item) = self.Conditions.Add(item)
        member this.Clear() = self.Conditions.Clear()
        member this.Contains(item) = self.Conditions.Contains(item)
        member this.CopyTo(conditions, index) = self.Conditions.CopyTo(conditions, index)
        member this.Remove(item) = self.Conditions.Remove(item)
        member this.GetEnumerator() = self.Conditions.GetEnumerator() :> IEnumerator<Condition>
        member this.GetEnumerator() = self.Conditions.GetEnumerator() :> IEnumerator 

2 个答案:

答案 0 :(得分:3)

这是因为IList有两个GetEnumerator方法,一个用于IEnumerable<T>接口,另一个用于非通用IEnumerable接口。

您可以添加此成员以实施IEnumerable

member this.GetEnumerator() = (this.Conditions :> IEnumerable).GetEnumerator()

答案 1 :(得分:2)

最简单的方法是

interface System.Collections.IEnumerable with
    member this.GetEnumerator() = this.Conditions.GetEnumerator() :> _