f#覆盖数组访问运算符。[]

时间:2011-05-28 13:30:58

标签: f#

在F#中,我想创建一种索引数组,因此我可以通过.[i].[index_names]以及带有索引..的切片表示法访问该元素是否可以像这样覆盖.[]?感谢。

1 个答案:

答案 0 :(得分:11)

在您的类型中定义重载的索引器:

type MyIndexedArray<'T>() = 
    member this.Item(i : int) : 'T = Unchecked.defaultof<_>
    member this.Item(name : string) : 'T = Unchecked.defaultof<_>
    member this.GetSlice(a : int option, b : int option) : 'T = Unchecked.defaultof<_>

let arr = new MyIndexedArray<int>()
let a = arr.[1]
let b = arr.["name"]
let c = arr.[1..2]
let d = arr.[1..]
let e = arr.[..3]
let f = arr.[*]