Share via


物件運算式

object expression 是一個運算式,它會建立編譯器產生的匿名物件類型 (基於現有的基底類型、介面或介面集) 的新執行個體。

語法

// 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 描述選擇性泛型型別參數。 arguments 僅適用於需要建構函式參數的類別類型。 member-definitions 會覆寫基底類別方法,或是從基底類別或介面實作抽象方法。

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

// 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() = () }

使用物件運算式

當您想要避免建立新具名類型所需的額外程式碼與額外負荷時,會使用物件運算式。 若您使用物件運算式將程式中建立的類型數目降至最低,則可以減少程式碼數目並防止不必要的類型激增。 您可以使用自訂現有類型的物件運算式,或針對手邊的特定案例提供適當的介面實作,而不是建立許多類型來處理特定情況。

另請參閱