对象初始化器是构造函数之外的一种选择。语法如下所示。你需要在花括号中提供一个逗号分隔的名称-值对列表,名称和值之间用=分隔:
public class Person
{
public string Name;
public string Address;
}
var person = new Person{Name="The President", Address = "Élysée Palace"};
集合也可以用这种方式初始化。通常,可以用下面这样的逗号分隔列表来实现:
IList<Person> people = new List<Person>{ new Person(), new Person{Name="Joe Shmo"}};
字典使用以下语法:
IDictionary<int, string> numbers = new Dictionary<int, string>{ [0] = "zero", [1] = "one"...};
// or
IDictionary<int, string> numbers = new Dictionary<int, string>{ {0, "zero" }, {1, "one"}...};
你被要求继续在网络身份验证系统上做一些工作。
开发期间,系统已经硬编码了管理员的身份。除此之外,高层还希望资深开发者也能享受同等的待遇。
管理员的详细信息如下:
| 电子邮件 | 眼睛颜色 | 人中宽度 | 姓名 | 地址 1 | 地址 2 |
|---|---|---|---|---|---|
| admin@ex.ism | green | 0.9 | Chanakya | Mumbai | India |
实现 Authenticator.Admin 属性,返回系统管理员的身份信息。姓名和地址的每一部分都应放在 NameAndAddress 列表的独立元素中。
var authenticator = new Authenticator();
authenticator.Admin;
// => {"admin@ex.ism", {"green", 0.9m}, ["Chanakya", "Mumbai", "India"]}
开发者的详细信息如下:
| 电子邮件 | 眼睛颜色 | 人中宽度 | 姓名 | 地址 1 | 地址 2 |
|---|---|---|---|---|---|
| bert@ex.ism | blue | 0.8 | Bertrand | Paris | France |
| anders@ex.ism | brown | 0.85 | Anders | Redmond | USA |
实现 Authenticator.Developers 属性,返回开发者的身份信息。字典的键是开发者的姓名。
var authenticator = new Authenticator();
authenticator.Developers;
// => ["Bertrand"] = {"bert@ex.ism", {"blue", 0.8m}, ["Bertrand", "Paris", "France"]},
// ["Anders"] = {"anders@ex.ism", {"brown", 0.85m}, ["Anders", "Redmond", "USA"]},