在seq builder中枚举时,F#如何知道bitArray元素是bool?

Art*_*ała 13 f#

    seq{
        for bit in BitArray(10) do 
        yield bit
    }
Run Code Online (Sandbox Code Playgroud)

bitbool类型的.我检查了ILSpy,并在其中一个闭包中添加了一个显式的强制转换.

BitArray仅实现普通(非通用)IEnumerable.F#如何知道它是一个bool

Rin*_*gil 13

根据F#4.1规范的第6.5.6节"序列迭代表达式",IEnumerable如果IEnumerable具有Itemobject类型的属性(突出显示我的),F#甚至会为非泛型转换:

以下形式的表达式是序列迭代表达式:

for exp in expr1 do expr2 done

该类型的是相同的返回类型当前在枚举值属性.但是,如果Current属性具有返回类型obj且集合类型ty 具有具有更具体(非对象)返回类型ty2Item属性, 则使用类型ty2,并插入动态强制转换以将v.Current转换为ty2.

如果我们查看源代码BitArray,我们看到它确实具有Item类型的属性bool:

public bool this[int index] {
        get {
            return Get(index);
        }
        set {
            Set(index,value);
        }
}
Run Code Online (Sandbox Code Playgroud)

因此,F#将bool在迭代时显式转换为.