简体   繁体   English

这是如何运作的? 到底是什么情况?

[英]How does this work? What exactly is happening?

I am learning Xamarin and I know the basics of C#. 我正在学习Xamarin,并且了解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 ? 什么是Children What is it getting assigned to? 它被分配给什么?

Children is not assigned to, but Children is initialized . Children未分配给,但Children初始化 It is more confusing as property `Children' is not browsable, so it does not appear in intellisense. 它更令人困惑,因为属性“ Children”不可浏览,因此它不会出现在智能感知中。

Children is IList<View> . ChildrenIList<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 您可以在这里查看示例, https://dotnetfiddle.net/8jln93

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM