選項Options

當命名值或F#變數的實際值可能不存在時, 會使用中的選項類型。The option type in F# is used when an actual value might not exist for a named value or variable. 選項具有基礎類型, 而且可以保留該類型的值, 或者可能沒有值。An option has an underlying type and can hold a value of that type, or it might not have a value.

備註Remarks

下列程式碼說明產生選項類型的函式。The following code illustrates a function which generates an option type.

let keepIfPositive (a : int) = if a > 0 then Some(a) else None

如您所見, 如果輸入a大於 0, Some(a)就會產生。As you can see, if the input a is greater than 0, Some(a) is generated. 否則, None就會產生。Otherwise, None is generated.

當選項None沒有實際的值時, 會使用此值。The value None is used when an option does not have an actual value. 否則, 運算式Some( ... )會為選項提供值。Otherwise, the expression Some( ... ) gives the option a value. Some trueNone在模式比對中很有用, exists如下列函式所示, 如果選項具有值false , 則會傳回, 如果不是, 則會傳回。The values Some and None are useful in pattern matching, as in the following function exists, which returns true if the option has a value and false if it does not.

let exists (x : int option) =
    match x with
    | Some(x) -> true
    | None -> false

使用選項Using Options

當搜尋未傳回相符的結果時, 通常會使用選項, 如下列程式碼所示。Options are commonly used when a search does not return a matching result, as shown in the following code.

let rec tryFindMatch pred list =
    match list with
    | head :: tail -> if pred(head)
                        then Some(head)
                        else tryFindMatch pred tail
    | [] -> None

// result1 is Some 100 and its type is int option.
let result1 = tryFindMatch (fun elem -> elem = 100) [ 200; 100; 50; 25 ]

// result2 is None and its type is int option.
let result2 = tryFindMatch (fun elem -> elem = 26) [ 200; 100; 50; 25 ]

在先前的程式碼中, 會以遞迴方式搜尋清單。In the previous code, a list is searched recursively. pred函式tryFindMatch會採用會傳回布林值的述詞函式, 以及要搜尋的清單。The function tryFindMatch takes a predicate function pred that returns a Boolean value, and a list to search. 如果找到滿足述詞的專案, 遞迴就會結束, 而且函數會傳回值做為運算式Some(head)中的選項。If an element that satisfies the predicate is found, the recursion ends and the function returns the value as an option in the expression Some(head). 當符合空的清單時, 遞迴就會結束。The recursion ends when the empty list is matched. 此時找不到值head , 而且None會傳回。At that point the value head has not been found, and None is returned.

許多F#搜尋集合中不一定存在option值的程式庫函數會傳回類型。Many F# library functions that search a collection for a value that may or may not exist return the option type. 依照try慣例, 這些函式會以前置詞開頭, Seq.tryFindIndex例如。By convention, these functions begin with the try prefix, for example, Seq.tryFindIndex.

當您嘗試建立值時可能會擲回例外狀況時, 選項也可能很有用, 例如。Options can also be useful when a value might not exist, for example if it is possible that an exception will be thrown when you try to construct a value. 下列程式碼範例會說明這點。The following code example illustrates this.

open System.IO
let openFile filename =
    try
        let file = File.Open (filename, FileMode.Create)
        Some(file)
    with
        | ex -> eprintf "An exception occurred with message %s" ex.Message
                None

openFile一個範例中的函式具有string -> File option型別, 因為File如果檔案成功開啟, 以及發生None例外狀況, 就會傳回物件。The openFile function in the previous example has type string -> File option because it returns a File object if the file opens successfully and None if an exception occurs. 視情況而定, 它可能不是適當的設計選擇來攔截例外狀況, 而不是讓它傳播。Depending on the situation, it may not be an appropriate design choice to catch an exception rather than allowing it to propagate.

此外, 仍然可以null將或值Some設為 null, 以作為選項的大小寫。Additionally, it is still possible to pass null or a value that is null to the Some case of an option. 這通常是避免的, 通常是在例行F#的程式設計中, 但可能是因為 .net 中參考型別的本質。This is generally to be avoided, and typically is in routine F# programming, but is possible due to the nature of reference types in .NET.

選項屬性和方法Option Properties and Methods

選項類型支援下列屬性和方法。The option type supports the following properties and methods.

屬性或方法Property or method 類型Type 描述Description
None 'T option 靜態屬性, 可讓您建立具有None值的選項值。A static property that enables you to create an option value that has the None value.
IsNoneIsNone bool true如果選項None具有值, 則傳回。Returns true if the option has the None value.
IsSomeIsSome bool 如果選項的值不None是, 則傳回。 trueReturns true if the option has a value that is not None.
部分Some 'T option 靜態成員, 它會建立值不None是的選項。A static member that creates an option that has a value that is not None.
Value 'T 傳回基礎值, 或System.NullReferenceException如果值為None, 則擲回。Returns the underlying value, or throws a System.NullReferenceException if the value is None.

選項模組Option Module

有一個模組選項, 其中包含對選項執行作業的實用函式。There is a module, Option, that contains useful functions that perform operations on options. 有些函式會重複屬性的功能, 但在需要函式的內容中很有用。Some functions repeat the functionality of the properties but are useful in contexts where a function is needed. IsSome選項。 isNone都是測試選項是否包含值的模組函式。Option.isSome and Option.isNone are both module functions that test whether an option holds a value. 選項。 get 會取得值 (如果有的話)。Option.get obtains the value, if there is one. 如果沒有值, 則System.ArgumentException會擲回。If there is no value, it throws System.ArgumentException.

如果Option.bind有值, 則 [系結函式] 會在值上執行函數。The Option.bind function executes a function on the value, if there is a value. 函式必須只接受一個引數, 而其參數類型必須是選項類型。The function must take exactly one argument, and its parameter type must be the option type. 函數的傳回值是另一個選項類型。The return value of the function is another option type.

選項模組也包含函式, 這些函式會對應至可供清單、陣列、序列和其他集合類型使用的函數。The option module also includes functions that correspond to the functions that are available for lists, arrays, sequences, and other collection types. 這些功能包括Option.mapOption.iterOption.forallOption.existsOption.foldBackOption.countOption.foldThese functions include Option.map, Option.iter, Option.forall, Option.exists, Option.foldBack, Option.fold, and Option.count. 這些函式可讓選項當做零或一個元素的集合使用。These functions enable options to be used like a collection of zero or one elements. 如需詳細資訊和範例, 請參閱清單中的集合函數討論。For more information and examples, see the discussion of collection functions in Lists.

轉換成其他類型Converting to Other Types

選項可以轉換成清單或陣列。Options can be converted to lists or arrays. 當選項轉換成其中一個資料結構時, 產生的資料結構會有零個或一個元素。When an option is converted into either of these data structures, the resulting data structure has zero or one element. 若要將選項轉換為數組, 請Option.toArray使用。To convert an option to an array, use Option.toArray. 若要將選項轉換為清單, 請Option.toList使用。To convert an option to a list, use Option.toList.

另請參閱See also