Dies ist ein object initializer - eingeführt in C# 3,0
Content = new Label {
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Text = "Hello word"
};
wird nur funktionieren, wenn Label
einen parameterlosen Konstruktor hat.
Wir können davon ausgehen, Label
etwa wie folgt aussieht:
public class Label
{
public Label()
{
//this empty ctor is not required by the compiler
//just here for illustration
}
public string HorizontalOptions {get;set}
public string VerticalOptions {get;set}
public string Text {get;set}
}
Die Objektinitialisierer wird die Einstellung von Eigenschaften, wenn es instanziiert wird.
Wenn jedoch Label
einen Parameter in dem Ctor, wie dies hat:
public class Label
{
public Label(string text)
{
Text = text
}
public string HorizontalOptions {get;set}
public string VerticalOptions {get;set}
public string Text {get;set}
}
dann wäre dies gleichbedeutend
Content = new Label("Hello World") { //notice I'm passing parameter to ctor here
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
};
Der Begriff bei Google ist [ "Objektinitialisierer"] (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initialisers) –
Es ist eine Ein-Liner-Verknüpfung zu 'new Label() {Property1 = Wert1, etc ...}; 'Der standardmäßige parameterlose Konstruktor wird aufgerufen. – bradbury9