[英]How does this work? What exactly is happening?
我正在學習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
? 它被分配給什么?
Children
未分配給,但Children
已初始化 。 它更令人困惑,因為屬性“ Children”不可瀏覽,因此它不會出現在智能感知中。
Children
為IList<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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.