c# 使用初始化器初始化对象

来源:互联网 发布:最优化书籍推荐 编辑:程序博客网 时间:2024/05/16 23:56
class Goods    {        private string strName;        public string Name        {            get { return strName; }            set { strName = value; }        }        private decimal decPrice;        public decimal Price        {            get { return decPrice; }            set { decPrice = value; }        }        private int intQuantity;        public int Quantity        {            get { return intQuantity; }            set { intQuantity = value; }        }    }    class Program    {        static void Main(string[] args)        {            var goods = new Goods            {                Name = "辐照度",                Price = 5,                Quantity = 3            };            Console.WriteLine("水冷日晒的情况" + goods.Quantity + "温度" + goods.Price + "" + goods.Name);            Console.Read();        }    }

以上为使用对象初始化器;下面为使用集合初始化器:

class Program    {        static void Main(string[] args)        {            //var goods = new Goods            //{            //    Name = "辐照度",            //    Price = 5,            //    Quantity = 3            //};            //Console.WriteLine("水冷日晒的情况" + goods.Quantity + "温度" + goods.Price + "" + goods.Name);            //Console.Read();            var list = new List<Goods>            {                new Goods{Name = "轿车", Price= 10000, Quantity = 2},                new Goods{Name = "电脑",Price = 5000, Quantity = 50},                new Goods {Name = "打印机", Price = 4000, Quantity = 5}            };            Console.WriteLine("公司近期打算采购以下商品:");            foreach (var item in list)            {                Console.WriteLine("价值为{0}的{1},采购数量为{2}", item.Price, item.Name, item.Quantity);            }            Console.Read();        }    }


0 0
原创粉丝点击