2007-08-08

C# 3.0 筆記: Automatic Properties, Object Initializers, Collection Initializers

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 ===
List ps = new List();

ps.Add(new Person { Name = "John", Age = 30 });
ps.Add(new Person { Name = "Mary", Age = 25 });
//=== Way 2 ===
List ps = new List {
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Mary", Age = 25 };

沒有留言: