对象初始化器
作用:用较少的代码创建一个新对象并为对象的若干属性和公共数据成员进行赋值。{ }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _09_对象初始化器
{
class Program
{
static void Main(string[] args)
{
//1)手动初始化Person实例的两个属性
Person p1 = new Person();
p1.Name = "陈如水";
p1.Age = 22;
//2)使用构造函数进行初始化
Person p2 = new Person("陈诗音", 23);
//3)使用对象初始化语法进行初始化
Person p3 = new Person()
{
Name = "陈诗悦",
Age = 24
};
//4)对象初始化器的好处就是用在集合初始化上,在创建SqlParameter的时候使用的比较多一些
List<Person> list = new List<Person>
{
new Person() {Name = "陈诗悦",Age = 24 },
new Person() {Name = "陈诗音",Age = 25 }
};
}
}
}
Person类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _09_对象初始化器
{
class Person
{
private string _name;
private int _age;
public Person()
{
}
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
public string Name
{
get; set;
}
public int Age
{
get; set;
}
}
}