代码
//匿名类型,匿名类
//必须初始化不能为null
//仍为强类型,只是由编译器去做了
//优于object,减少了boxing、unboxing
var i = 10;
Console.WriteLine(i);
var user = new { Name = "steve", Age = 10 };
Console.WriteLine(user.Name + " " + user.Age);
//自动属性
/// <summary>
/// 自动属性
/// </summary>
class Student
{
public string Name
{
get;
set;
}
//Age为只读属性
public int Age
{
get;
private set;
}
}
//以上Student类等同于:
/// <summary>
/// 自动属性
/// </summary>
class Student
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
}
//对象初始化器
Student zs = new Student { Name = "steve", Age = 10 };
Console.WriteLine(zs.Name);
//集合初始化器
List<Student> list = new List<Student> { new Student { Name = "bob", Age = 11 }, new Student { Name = "tom", Age = 12 } };