class Program { static void Main(string[] args) { Employee e = new Employee() { Name = "Jeff", Age = 45 };//省略圆括号,默认调用无参构造器 Employee e1 = new Employee { Name = "Jeff", Age = 45 }; String s = new Employee() { Name = "Jeff", Age = 45 }.ToString().ToUpper(); } } public class Employee {//定义访问器 public String Name { get; set; } public Int32 Age { get; set; } }
class Program { static void Main(string[] args) { Classroom classroom = new Classroom {//集合必须实现了Add方法才能使用集合初始化器 //使用集合初始化语法向集合中添加数据项 Students = { "Jeff", "Kristin", "Aidan", "Grant" } };// 显示教室中的4个学生 foreach (var student in classroom.Students) Console.WriteLine(student); } } public sealed class Classroom { private List<String> m_students = new List<String>(); public List<String> Students { get { return m_students; } } public Classroom() { } }
//集合的Add方法有多个参数时,可用{参数1,参数2,...},... var table = new Dictionary<String, Int32> { { "Jeffrey", 1 }, { "Kristin", 2 }, { "Aidan", 3 }, { "Grant", 4 } };//上面的代码等效于 var table = new Dictionary<String, Int32>(); table.Add("Jeffrey", 1); table.Add("Kristin", 2); table.Add("Aidan", 3); table.Add("Grant", 4);
// 定义类型,构造实例,并初始化属性 // 编译器自动推断类型 var o1 = new { Name = "Jeff", Year = 1964 };// 在控制台上显示属性 Console.WriteLine("Name={0}, Year={1}", o1.Name, o1.Year);// 错误: 匿名属性不可写,仅可读 //o1.Name = "aa";// 让编译器根据变量名推断属性名和类型 String Name = "Grant"; DateTime dt = DateTime.Now;// 有两个属性的匿名类型 // 1. String Name属性设为"Grant" // 2. Int32 Year属性设为dt中的年份 var o2 = new { Name, dt.Year };// 因为o1和o2的结构相同,属性相同可以进行赋值和相等判断 Console.WriteLine("Objects are equal: " + o1.Equals(o2)); o1 = o2;//由于类型的同一性,可以创建一个隐式类型的数组 var people = new[] { o1, new { Name = "Kristin", Year = 1970 }, new { Name = "Aidan", Year = 2003 }, new { Name = "Grant", Year = 2008 } };//遍历匿名类型的对象构成的数组(var 是必须的) foreach (var person in people) Console.WriteLine("Person={0}, Year={1}", person.Name, person.Year);//匿名类型经常与LINQ(Language Intergrated Query,语言集成查询)配合使用 //返回“我的文档”文件夹中过去7天修改过的所有文件 String myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var query = from pathname in Directory.GetFiles(myDocuments) let LastWriteTime = File.GetLastWriteTime(pathname) where LastWriteTime < (DateTime.Now - TimeSpan.FromDays(7)) orderby LastWriteTime select new { Path = pathname, LastWriteTime };//匿名类型的对象构成的集合 foreach (var file in query) Console.WriteLine("LastWriteTime={0}, Path={1}", file.LastWriteTime, file.Path);
匿名类型的实例不能泄露到方法外部。方法原型不能接受匿名类型的参数,因为无法指定匿名类型。类似地,方法也不能返回对匿名类型的引用。虽然可以将匿名类型的实例视为一个Object(所有匿名类型都从Object派生),但没办法将Object类型的变量转型回匿名类型,因为不知道匿名类型在编译时的名称。