共用方式為


索引屬性 (F#)

「索引屬性」(Indexed Property) 是對已排序資料提供類似陣列存取的屬性。

// 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 時,編譯器會將屬性當做預設索引屬性。 「預設索引屬性」(Default Indexed Property) 就是您可以在物件執行個體上使用類似陣列語法來存取的屬性。 例如,如果 obj 是定義此屬性之型別的物件,obj.[index] 語法會用來存取屬性。

存取非預設索引屬性的語法是在括號中提供屬性名稱和索引。 例如,如果屬性為 Ordinal,您可以撰寫 obj.Ordinal(index) 來存取此屬性。

無論使用哪種形式,都務必針對索引屬性上的 set 方法使用局部調用形式。 如需局部調用函式的詳細資訊,請參閱函式 (F#)

範例

下列程式碼範例說明如何定義和使用具有 set 和 get 方法的預設和非預設索引屬性。

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 方法必須有兩個局部調用引數,第一個是包含索引鍵的 Tuple,第二個是設定的值。

下列程式碼範例中,會示範有多個索引變數之索引屬性的用法。

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#)