0
点赞
收藏
分享

微信扫一扫

C# 对象和集合的初始化器


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication16
{
/// <summary>
/// 商品类
/// </summary>
public class Product
{
/// <summary>
/// 商品编号
/// </summary>
public int ProductID { get; set; }
/// <summary>
/// 商品名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 商品描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 商品价格
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// 商品分类
/// </summary>
public string Category { set; get; }
}
class Program
{
static void Main(string[] args)
{
//对象初始化器的使用 (可只给部分字段赋值)
Product product = new Product { ProductID = 1234, Name = "西瓜", Price = 2.3M };//创建并初始化一个实例

//集合初始化器的使用
List<Product> proList = new List<Product> {
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<string, int> fruitDic = new Dictionary<string, int>() {
{ "apple", 10 },
{ "orange", 20 },
{ "plum", 30 }
};
*/
}
}
}


举报

相关推荐

0 条评论