C# Class 没有显式构造函数且只读 属性
C# Class without explicit constructor and read only property
谁能解释一下这段代码是如何工作的?
public class Person
{
readonly List<Person> _children = new List<Person>();
public IList<Person> Children
{
get { return _children; }
}
public string Name { get; set; }
}
public static Person GetFamilyTree()
{
return new Person
{
Name = "David Weatherbeam",
Children =
{
new Person
{
Name="Alberto Weatherbeam",
Children=
{
new Person
{
Name="Jenny van Machoqueen",
Children=
{
new Person
{
Name="Nick van Machoqueen",
},
new Person
{
Name="Matilda Porcupinicus",
}
}
}
}
}
}
};
}
'Children' 属性 是 'read-only'(因为它没有 setter)。
'GetFamilyTree' 函数似乎使用了一个隐式初始化程序,它适用于 'Name' 属性,因为它可以在 'Person' 之外访问,但是 'Children' 属性可以在这个函数中赋值吗?
感谢您的解释。
干杯。
这种有点令人困惑的对象初始化语法 检索 具有 get
访问器的集合,并对集合使用 public Add
方法。它之所以有效,是因为 属性 IList<Person>
的编译时类型具有(继承)a public Add
method 和兼容的签名(采用 Person
参数)。
谁能解释一下这段代码是如何工作的?
public class Person
{
readonly List<Person> _children = new List<Person>();
public IList<Person> Children
{
get { return _children; }
}
public string Name { get; set; }
}
public static Person GetFamilyTree()
{
return new Person
{
Name = "David Weatherbeam",
Children =
{
new Person
{
Name="Alberto Weatherbeam",
Children=
{
new Person
{
Name="Jenny van Machoqueen",
Children=
{
new Person
{
Name="Nick van Machoqueen",
},
new Person
{
Name="Matilda Porcupinicus",
}
}
}
}
}
}
};
}
'Children' 属性 是 'read-only'(因为它没有 setter)。 'GetFamilyTree' 函数似乎使用了一个隐式初始化程序,它适用于 'Name' 属性,因为它可以在 'Person' 之外访问,但是 'Children' 属性可以在这个函数中赋值吗?
感谢您的解释。 干杯。
这种有点令人困惑的对象初始化语法 检索 具有 get
访问器的集合,并对集合使用 public Add
方法。它之所以有效,是因为 属性 IList<Person>
的编译时类型具有(继承)a public Add
method 和兼容的签名(采用 Person
参数)。