using System;
using System.Collections.Generic;
class Parent
{
public Child Child { get; set; }
}
class Child
{
public List<string> Strings { get; set; }
}
static class Program
{
static void Main() {
// bad object initialization
var parent = new Parent() {
Child = {
Strings = { "hello", "world" }
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
上面的程序编译很好,但在运行时崩溃,而Object引用没有设置为对象的实例.
如果您在上面的代码段中注意到,我在初始化子属性时省略了new.
显然,正确的初始化方法是:
var parent = new Parent() {
Child = new Child() {
Strings = new List<string> { …Run Code Online (Sandbox Code Playgroud) 的readonly Children属性StackLayout为类型IList<View>。令我惊讶的是,知道Children可以分配给集合初始值设定项,如以下代码片段所示(受Xamarin.Forms文档给出的示例启发):
public MainPage()
{
StackLayout sl = new StackLayout
{
Children =
{
new Label{Text="Start",HorizontalOptions=LayoutOptions.Start}
}
};
}
Run Code Online (Sandbox Code Playgroud)
为什么当它是只读属性时才能分配它?
接下来,我做了一个反例如下。在这里,编译器抱怨这Children是一个只读属性。这是可以理解的,但前一个不是。你能告诉我为什么吗?
public MainPage()
{
IList<Label> labels = new List<Label>
{
new Label{Text="Start",HorizontalOptions=LayoutOptions.Start}
};
StackLayout sl = new StackLayout
{
Children = labels
};
}
Run Code Online (Sandbox Code Playgroud)