xiacy

导航

8.2 简化的初始化

public class Person
{
    public int Age { get; set; }
    public string Name { get; set; }

    List<Person> friends = new List<Person>();
    public List<Person> Friends { get { return friends; } }

    Location home = new Location();
    public Location Home { get { return home; } }

    public Person() { }
    public Person(string name)
    { Name = name; }
}

public class Location
{
    public string Country { get; set; }
    public string Town { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Person tom1 = new Person();
        tom1.Name = "tom1";
        tom1.Age = 20;

        Person tom2 = new Person("tom2");
        tom2.Age = 22;

        Person tom3 = new Person() { Name = "tom3", Age = 63 };
        Person tom4 = new Person { Name = "tom4", Age = 33 };
        Person tom5 = new Person("tom5") { Age = 31 };

        Person[] family = new Person[]
        {
            new Person{Name="holle",Age=34},
            new Person {Name ="aaa",Age=32},
            new Person{Name="holle",Age=34},
            new Person {Name ="aaa",Age=32},
            new Person{Name="holle",Age=34},
            new Person {Name ="aaa",Age=32},
            new Person{Name="holle",Age=34},
            new Person {Name ="aaa",Age=32}
        };

        Person tom = new Person
        {
            Name = "tom",
            Age = 15,
            Home = { Town = "reading", Country = "UK" },
            Friends =
            {
                new Person{Name="Alberto"},
                new Person("max"),
                new Person { Name="zak",Age=4},
                new Person("ben"),
                new Person("alice")
                {
                    Age=6,
                    Home={Town="twyford",Country="UK"}
                }
            }
        };

        Console.ReadKey();
    }
}

 

posted on 2012-05-29 23:22  xiacy  阅读(184)  评论(0编辑  收藏  举报