您的位置:首页 > 编程语言 > C#

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

2015-10-20 10:22 525 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: