对于 fsharp 数组,我们可以执行以下操作:
let tt = Array.zeroCreate 10
tt.[5] <- 4
Console.WriteLine("{0}", tt.[5])
结果将为 4
我想实现我自己的提供类似接口(interface)的类。 作为示例,我写了这个:
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
.
如何实现这样的接口(interface)?
谢谢。
最佳答案
您可以像这样使用 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
关于f# - fsharp 通过方括号引用来赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31280932/