索引属性 (F#)

索引属性是可用来提供对有序数据进行类似数组的访问的属性。

// Indexed property that has both get and set defined.
member self-identifier.PropertyName
   with get(index-variable) =
      get-function-body
  and set index-variables value-variables =
      set-function-body

// Indexed property that has get only.
member self-identifier.PropertyName(index-variable) =
      get-function-body

// Alternative syntax for indexed property with get only
member self-identifier.PropertyName
   with get(index-variables) =
      get-function-body

// Indexed property that has set only.
member self-identifier.PropertyName
   with set index-variables value-variables = 
      set-function-body

备注

以上三种语法形式分别演示了如何定义具有 get 和 set 方法的索引属性、仅具有 get 方法的索引属性以及仅具有 set 方法的索引属性。 也可以将所示的仅限 get 的语法和仅限 set 的语法组合起来,生成同时具有 get 和 set 方法的属性。 通过后一种形式,可以为 get 和 set 方法设置不同的可访问性修饰符和特性。

如果 PropertyName 为 Item,则编译器会将属性视为默认索引属性。 默认索引属性是指您可以通过对对象实例使用类似数组的语法来访问的属性。 例如,如果 obj 是定义此属性的类型的对象,则可使用语法 obj.[index] 来访问此属性。

用于访问非默认索引属性的语法需提供属性的名称和用圆括号括起来的索引。 例如,如果属性为 Ordinal,则您需要编写 obj.Ordinal(index) 语法来访问该属性。

无论采用哪种形式,对于索引属性上的 set 方法,均应始终使用扩充形式。 有关扩充函数的信息,请参见函数 (F#)

示例

下面的代码示例演示具有 get 和 set 方法的默认索引属性和非默认索引属性的定义和用法。

type NumberStrings() =
   let mutable ordinals = [| "one"; "two"; "three"; "four"; "five";
                             "six"; "seven"; "eight"; "nine"; "ten" |]
   let mutable cardinals = [| "first"; "second"; "third"; "fourth";
                              "fifth"; "sixth"; "seventh"; "eighth";
                              "ninth"; "tenth" |]
   member this.Item
      with get(index) = ordinals.[index]
      and set index value = ordinals.[index] <- value
   member this.Ordinal
      with get(index) = ordinals.[index]
      and set index value = ordinals.[index] <- value
   member this.Cardinal
      with get(index) = cardinals.[index]
      and set index value = cardinals.[index] <- value

let nstrs = new NumberStrings()
nstrs.[0] <- "ONE"
for i in 0 .. 9 do
  printf "%s " (nstrs.[i])
printfn ""

nstrs.Cardinal(5) <- "6th"

for i in 0 .. 9 do
  printf "%s " (nstrs.Ordinal(i))
  printf "%s " (nstrs.Cardinal(i))
printfn ""

Output

ONE two three four five six seven eight nine ten
ONE first two second three third four fourth five fifth six 6th
seven seventh eight eighth nine ninth ten tenth

具有多个索引变量的索引属性

索引属性可以具有多个索引变量。 在这种情况下,使用此类属性时应用逗号将各变量隔开。 此类属性中的 set 方法必须具有两个扩充参数:第一个参数是包含键的元组,第二个参数是所设置的值。

下面的代码示例演示如何使用带有多个索引变量的索引属性。

open System.Collections.Generic

type SparseMatrix() =
    let mutable table = new Dictionary<(int * int), float>()
    member this.Item
        with get(key1, key2) = table.[(key1, key2)]
        and set (key1, key2) value = table.[(key1, key2)] <- value

let matrix1 = new SparseMatrix()
for i in 1..1000 do
    matrix1.[i, i] <- float i * float i

请参见

其他资源

成员 (F#)