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();
        }
    }

以上代码中,同一个地方用了两种方式给对象的属性或字段进行初始化。可以看到,构造函数是最先执行的。即花括号{}里的赋值语句赋的值是对象初始化最终的值。

其实:

1 test b = new test("22") { aa = 1, bb = "11", cc = true, dd = "224" };
2 
3 等效于
4 
5 test b = new test("22");
6 b.aa = 1; b.bb = "11"; b.cc = true; b.dd = "224";
原文地址:https://www.cnblogs.com/chenpanpan/p/14506756.html