オブジェクト式
"オブジェクト式" は、既存の基本型、インターフェイス、または一連のインターフェイスに基づいて、コンパイラー生成の匿名のオブジェクト型の新しいインスタンスを作成する式です。
構文
// 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 ]
}
Remarks
前の構文で、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() = () }
オブジェクト式の使用
新しい名前付きの型を作成するために必要な追加のコードとオーバーヘッドを回避する必要がある場合は、オブジェクト式を使用します。 オブジェクト式を使用して、プログラムで作成される型の数を最小限に抑えると、コードの行数を減らし、型の不必要な急増を防ぐことができます。 特定の状況に対処するためだけに多くの型を作成する代わりに、既存の型をカスタマイズするオブジェクト式を使用するか、目の前の特定のケースに適したインターフェイスの実装を提供することができます。
関連項目
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
.NET feedback
The .NET documentation is open source. Provide feedback here.
フィードバック
フィードバックの送信と表示