I am learning Xamarin and I know the basics of C#. One of the first codes I encounter is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace Hello
{
public class App : Application
{
public App()
{
// The root page of your application
MainPage = new ContentPage
{
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = "Welcome to Xamarin Forms!"
}
}
}
};
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
The part where I have a problem is
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = "Welcome to Xamarin Forms!"
}
I don't understand what's happening here. What is Children
? What is it getting assigned to?
Children
is not assigned to, but Children
is initialized . It is more confusing as property `Children' is not browsable, so it does not appear in intellisense.
Children
is IList<View>
.
You can initialize collection like this...
List<string> list = new List<string>{
"s1",
"s2",
"s3"
};
which is equivalent to
List<string> list = new List<string>();
list.Add("s1");
list.Add("s2");
list.Add("s3");
Similarly
Children = {
new Label{
}
}
is equivalent to
Children.Add(new Label{ });
However, there is no official document about how to initialize collection property like this, but it seems compiler converts expression cleverly. I tried to compile and it seems it did work correctly.
You can see an example here, https://dotnetfiddle.net/8jln93
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.