C#雜記-簡化的初始化


對象說明

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;}
}
View Code

--------------------------

初始化

Person tom1 = new Person();
tom1.Age=10;
tom1.Name="Tom";

Person tom2 = new Person("Tom");
tom2.Age=10;

這是最典型的兩種對象初始化的表達式。一種使用無參構造函數,一種使用有參構造函數。

對象初始化加上屬性賦值的多語句能用一條語句寫出來嗎?

可以。對象初始化表達式

Person tom3 = new Person(){ Name="Tom",Age=10};
Person tom4 = new Person("Tom"){Age=10};
person tom5 = new Person{Name="Tom",Age=10};

一行代碼實現了多行代碼的操作,用的是表達式,可以干很多事情的。

Person[] family = new Person[]
{
    new Person{Name="1",Age=1},
    new Person{Name="2",Age=2},
    new Person{Name="3",Age=3},
    new Person{Name="4",Age=4}
};

嵌套對象的初始化

Person tom = new Person
{
    Name="Tom",
    Age = 10,
    Home = {Town = "a" , Country = "b"},
    Friends = 
    {
        new Person{Name="a",Age=10},
        new Person
        {
            Name="b",
            Age = 10,
            Home=
            {
                 Town = "b",
                 Country = "c"
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM