class test:IEquatable<test> { public int aa { get; set; } public string bb { get; set; } public bool cc { get; set; } public string dd; public test(string dd) { this.dd = dd; } public bool Equals(test other) { return (this.aa == other.aa && this.bb == other.bb && this.cc == other.cc && this.dd == other.dd); } } class Program { static void Main(string[] args) { test a = new test("22") { aa = 1, bb = "11", cc = true, dd = "22" }; test b = new test("22") { aa = 1, bb = "11", cc = true, dd = "224" }; Console.WriteLine(a.Equals(b)); ReadLine(); } }
以上代碼中,同一個地方用了兩種方式給對象的屬性或字段進行初始化。可以看到,構造函數是最先執行的。即花括號{}里的賦值語句賦的值是對象初始化最終的值。
其實:
test b = new test("22") { aa = 1, bb = "11", cc = true, dd = "224" }; 等效於 test b = new test("22"); b.aa = 1; b.bb = "11"; b.cc = true; b.dd = "224";
