c#對象初始化


 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";

 


免責聲明!

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



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