オブジェクト初期化子は、コンストラクターに代わる書き方です。構文は次のとおりです。波括弧({})の中に、=で区切った名前と値のペアを、カンマで区切って並べます。
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"}...};
ネットワーク認証システムの作業を、もう少し進めることになりました。
開発中は管理者の識別情報をシステムにハードコードしていますが、それに加えて、上層部はシニアエンジニアにも同じ扱いをするよう求めています。
管理者の情報は次のとおりです。
| Eye Color | Philtrum Width | Name | Address 1 | Address 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"]}
エンジニアたちの情報は次のとおりです。
| Eye Color | Philtrum Width | Name | Address 1 | Address 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"]},