fsharp通过方括号引用赋值

时间:2015-07-07 23:09:25

标签: f#

对于fsharp数组,我们可以执行以下操作:

let tt = Array.zeroCreate 10 
tt.[5] <- 4
Console.WriteLine("{0}", tt.[5])

结果将是4

我想实现我自己的类,提供类似的接口。 作为样本,我写了这个:

type MyByteArray = class
    val Data : byte[]

    new (size) =
        {
            Data = Array.init size (fun x -> byte(x))
        }

    member this.Item (id) = 
        this.Data.[id]
end

let test = MyByteArray 5
Console.WriteLine("{0}", test.[2]) /// <- this one woks
test.[2] <- 33uy /// <- this one fails

这可以通过[]接收项目,但不能将其设置为item.[id] <- newValue

如何实现此类界面?

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用getter和setter定义索引器,如下所示:

member this.Item 
  with get id = this.Data.[id]
  and set id v = this.Data.[id] <- v

如果我正在编写代码,我还会使用主构造函数语法:

type MyByteArray(size) =
  let data = Array.init size (fun x -> byte(x))  
  member this.Item 
    with get(id) = data.[id]
    and set id v = data.[id] <- v