本文共 1928 字,大约阅读时间需要 6 分钟。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication16{ ////// 商品类 /// public class Product { ////// 商品编号 /// public int ProductID { get; set; } ////// 商品名称 /// public string Name { get; set; } ////// 商品描述 /// public string Description { get; set; } ////// 商品价格 /// public decimal Price { get; set; } ////// 商品分类 /// public string Category { set; get; } } class Program { static void Main(string[] args) { //对象初始化器的使用 (可只给部分字段赋值) Product product = new Product { ProductID = 1234, Name = "西瓜", Price = 2.3M };//创建并初始化一个实例 //集合初始化器的使用 ListproList = new List { new Product { ProductID = 1234, Name = "西瓜", Price = 2.3M }, new Product { ProductID = 2345, Name = "苹果", Price = 5.9M }, new Product { ProductID = 3456, Name = "樱桃", Price = 4.6M } }; //打印 Console.WriteLine("对象初始化器:{0} {1} {2}", product.ProductID, product.Name, product.Price); foreach (Product p in proList) { Console.WriteLine("集合初始化器:{0} {1} {2}", p.ProductID, p.Name, p.Price); } Console.ReadKey(); /* 另外还有一些其它类型也可以使用初始化器,如下: //数组使用初始化器 string[] fruitArray = {"apple","orange","plum" }; //匿名类型使用初始化器 var books = new { Title = "ASP.NET MVC 入门", Author = "小王", Price = 20 }; //字典类型使用初始化器 Dictionary fruitDic = new Dictionary () { { "apple", 10 }, { "orange", 20 }, { "plum", 30 } }; */ } }}
转载地址:http://itdaf.baihongyu.com/