一种简单的对象赋值方法,定义实例后以{}赋值,比传统方法更简洁

public class Rectangle
    {
        public Point TopLeft { get; set; }
        public Point BottomRight { get; set; }
    }

    static void CompareObjectInitMethods()
    {
        // 传统初始化方法
        Rectangle r = new Rectangle();
        Point p1 = new Point();
        p1.X = 10;
        p1.Y = 10;
        r.TopLeft = p1;
        Point p2 = new Point();
        p2.X = 20;
        p2.Y = 20;
        r.BottomRight = p2;

        // 对象初始化语法
        Rectangle r2 = new Rectangle
        {
            TopLeft = new Point { X = 10, Y = 10 },
            BottomRight = new Point { X =   20, Y = 20 }
        };
    }

类似于数组、序列的初始化:

// 初始化标准数组
            int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            // 初始化一个ArrayList
            ArrayList list = new ArrayList { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            // 初始化一个List<T>泛型容器
            List<int> list2 = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            // 如果容器存放的是非简单对象
            List<Point> pointList = new List<Point>
            {
                new Point { X = 2, Y = 2},
                new Point { X = 3, Y = 3}
            };

posted on 2017-09-10 09:11  mol1995  阅读(197)  评论(0编辑  收藏  举报

导航