码迷,mamicode.com
首页 > Windows程序 > 详细

c#对象初始化

时间:2016-08-26 18:30:20      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

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

 

c#对象初始化

标签:

原文地址:http://www.cnblogs.com/silverzd/p/5810764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!