zoukankan      html  css  js  c++  java
  • 一种简单的对象赋值方法,定义实例后以{}赋值,比传统方法更简洁

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

  • 相关阅读:
    python常用模块②
    python常用模块①
    面向对象相关部分双下划线方法补充
    面向对象进阶 上
    面向对象初识④
    面向对象初识③
    综合架构-负载均衡
    wecent 搭建
    综合架构--存储
    综合架构--备份
  • 原文地址:https://www.cnblogs.com/mol1995/p/7500182.html
Copyright © 2011-2022 走看看