1. Automatic Properties 2. Object Initializers 3. Collection Initializers 1. Automatic Properties
//=== BEFORE === public class Person { private string _name; private int _age; public string Name { get { return _name; } set { _name = value; } } public int Age { get { return _age; } set { _age = value; } } }
//=== AFTER === public class Person { public string Name { get; set; } public int Age { get; set; } }2. Object Initializers
//=== BEFORE === Person p = new Person(); p.Name = "John"; p.Age = 30;
//=== AFTER === Person p = new Person { Name = "John", Age = 30 };3. Collection Initializers
//=== Way 1 === Listps = new List (); ps.Add(new Person { Name = "John", Age = 30 }); ps.Add(new Person { Name = "Mary", Age = 25 });
//=== Way 2 === Listps = new List { new Person { Name = "John", Age = 30 }, new Person { Name = "Mary", Age = 25 };
沒有留言:
張貼留言