Expresiones de objeto

Una expresión de objeto es una expresión que crea una nueva instancia de un tipo de objeto anónimo generado por compilador basado en un tipo base, interfaz o conjunto de interfaces existente.

Sintaxis

// 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 ]
}

Comentarios

En la sintaxis anterior, typename representa un tipo de clase o un tipo de interfaz existente. type-params describe los parámetros de tipo genérico opcionales. Los elementos arguments solo se usan para los tipos de clase, que requieren parámetros de constructor. Los elementos member-definitions son invalidaciones de métodos de clase base o implementaciones de métodos abstractos de una clase base o una interfaz.

En el ejemplo siguiente se muestran varios tipos diferentes de expresiones de objeto.

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

Uso de expresiones de objeto

Las expresiones de objeto se usan cuando se quiere evitar el código adicional y la sobrecarga necesarios para crear un nuevo tipo con nombre. Si usa expresiones de objeto para minimizar el número de tipos creados en un programa, puede reducir el número de líneas de código y evitar la proliferación innecesaria de tipos. En lugar de crear muchos tipos solo para controlar situaciones específicas, puede usar una expresión de objeto que personalice un tipo existente o proporcione una implementación adecuada de una interfaz para el caso específico en cuestión.

Vea también