共用方式為


物件表達式

物件表達式是一種表達式,會根據現有的基底類型、介面或介面集,建立編譯程式產生的匿名物件類型的新實例。

語法

// When typename is a class:
{ new typename [type-params]arguments with
    member-definitions
    [ additional-interface-definitions ]
}
// When typename is not a class:
{ new typename [generic-type-args] with
    member-definitions
    [ additional-interface-definitions ]
}

備註

在上一個語法中, typename 代表現有的類別類型或介面類型。 type-params 描述選擇性的泛型類型參數。 自變數僅適用於需要建構函式參數的類別類型。 成員定義是基類方法的覆寫,或從基類或介面實作抽象方法。

下列範例說明數種不同類型的物件表達式。

// This object expression specifies a System.Object but overrides the
// ToString method.
let obj1 = { new System.Object() with member x.ToString() = "F#" }
printfn $"{obj1}"

// This object expression implements the IFormattable interface.
let delimiter(delim1: string, delim2: string, value: string) =
    { new System.IFormattable with
        member x.ToString(format: string, provider: System.IFormatProvider) =
            if format = "D" then
                delim1 + value + delim2
            else
                value }

let obj2 = delimiter("{","}", "Bananas!");

printfn "%A" (System.String.Format("{0:D}", obj2))

// Define two interfaces
type IFirst =
  abstract F : unit -> unit
  abstract G : unit -> unit

type ISecond =
  inherit IFirst
  abstract H : unit -> unit
  abstract J : unit -> unit

// This object expression implements both interfaces.
let implementer() =
    { new ISecond with
        member this.H() = ()
        member this.J() = ()
      interface IFirst with
        member this.F() = ()
        member this.G() = () }

使用物件表達式

當您想要避免建立新的具名型別所需的額外程式代碼和額外負荷時,請使用物件表達式。 如果您使用物件表示式將程式中建立的類型數目降到最低,您可以減少程式代碼行數,並防止不必要的類型擴散。 您可以使用物件表達式來自定義現有類型,或針對手邊的特定案例提供適當的介面實作,而不是只建立許多類型來處理特定情況。

另請參閱