这是如何运作的?究竟发生了什么?

时间:2017-01-01 13:38:54

标签: c# xamarin xamarin.forms

我正在学习Xamarin,我知道C#的基础知识。我遇到的第一个代码之一是

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

我遇到问题的部分是

Children = {
    new Label {
        HorizontalTextAlignment = TextAlignment.Center,
        Text = "Welcome to Xamarin Forms!"
}

我不明白这里发生了什么。什么是Children?分配给它的是什么?

1 个答案:

答案 0 :(得分:1)

未分配

Children,但Children 已初始化。由于“儿童”属性不可浏览,所以它更加令人困惑,因此它不会出现在智能感知中。

ChildrenIList<View>

您可以像这样初始化集合......

List<string> list = new List<string>{
     "s1",
     "s2",
     "s3"
};

相当于

List<string> list = new List<string>();
list.Add("s1");
list.Add("s2");
list.Add("s3");

同样

Children = {
    new Label{
    }
}

相当于

Children.Add(new Label{  });

但是,没有关于如何初始化集合属性的官方文档,但似乎编译器巧妙地转换表达式。我试图编译它似乎它确实正常工作。

您可以在此处查看示例https://dotnetfiddle.net/8jln93

相关问题