我正在尝试在不实现它的外部类型上实现ToEnumerable属性。我无法让代码工作。
所以我愚蠢地添加了一个无类型的 GetEnumerator 属性,并添加了ToComparable的代码以获得指导。但是,我不知道如何为计数器存储可变状态。
pb是匿名类吗?
你会怎么做?
open System
open System.Collections
open System.Collections.Generic
type Bloomberglp.Blpapi.Element with
//**WORKS OK**
member this.ToComparable:IComparer<Bloomberglp.Blpapi.Element> = {
new IComparer<Bloomberglp.Blpapi.Element> with
member this.Compare(x, y) = x.NumValues.CompareTo(y.NumValues)
}
//**WORKS (sort of) OK without storing the state**
member this.GetEnumerator2:IEnumerator = {
//let mutable i =0
new IEnumerator with
member this2.Reset() =
i <- 0;
()
member this2.MoveNext() =
if i < n then
i <- i + 1
true
else
false
member this2.Current
with get() =
this.GetElement(0) :> obj
}
答案 0 :(得分:2)
假设NumValues
是计数,你可以这样做:
type Bloomberglp.Blpapi.Element with
member this.GetEnumerator() =
(Seq.init this.NumValues this.GetElement).GetEnumerator()
这会返回IEnumerator<'T>
,其中'T
是GetElement
的返回类型。
答案 1 :(得分:1)
回到最初为类型添加ToEnumerable
属性的想法,我可能将属性命名为AsEnumerable
或AsSeq
,因为Seq是IEnumerable的F#术语,并实现它像这样的东西:
type Bloomberglp.Blpapi.Element with
member this.AsEnumerable =
seq { for i = 0 to this.NumValues - 1 do
yield this.GetElement(i) }
或者你可以用Seq.init
做丹尼尔建议:
type Bloomberglp.Blpapi.Element with
member this.AsEnumerable =
Seq.init this.NumValues this.GetElement