匿名类型由var、赋值运算符=和一个非空初始值(或以new开头的初始化项)组成。
特性:
- 支持简单类型(一个非空初始值)和复杂类型(一个以new开头的初始化项)
- 匿名类型的属性是只读的,没有属性设置器,一旦被初始化就不可更改
- 匿名类型可以在循环中用作初始化器
- 匿名类型支持智能感知
- 匿名类型也可以拥有方法
匿名类型可以被用于存储LINQ查询结果的场景中,例:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 List<Employee> employeeList = new List<Employee>() 6 { 7 new Employee(){Name="John",DepaermentID=1}, 8 new Employee(){Name="Jake",DepaermentID=2}, 9 new Employee(){Name="Rose",DepaermentID=2} 10 }; 11 12 List<Department> departmentList = new List<Department>() 13 { 14 new Department(){Name="Technology",ID=1}, 15 new Department(){Name="Sales",ID=2} 16 }; 17 //使用LINQ查询,结果赋值给匿名类型employeeWithDepartmentList 18 var employeeWithDepartmentList = from emp in employeeList 19 join dep in departmentList on emp.DepaermentID equals dep.ID 20 select new { EmployeeName = emp.Name, DepaertmentName = dep.Name }; 21 foreach (var item in employeeWithDepartmentList) 22 { 23 Console.WriteLine(item.ToString()); 24 Console.WriteLine(string.Format("{0}\t{1}", item.EmployeeName, item.DepaertmentName)); 25 } 26 Console.Read(); 27 } 28 } 29 30 class Employee 31 { 32 public int DepaermentID { get; set; } 33 public string Name { get; set; } 34 } 35 class Department 36 { 37 public int ID { get; set; } 38 public string Name { get; set; } 39 }
运行结果:
{ EmployeeName = John, DepaertmentName = Technology } John Technology { EmployeeName = Jake, DepaertmentName = Sales } Jake Sales { EmployeeName = Rose, DepaertmentName = Sales } Rose Sales
上面代码声明了Employee类和Department类,Employee类中的DepartmentID属性对应着Department类里的ID属性。
LINQ查询找出每个员工对应的部门,然后new一个新的类,该类具有EmployeeName和DepartmentName这两个属性,分别存放员工名字和部门名称。根据结果赋值给匿名类型employeeWithDepartmentList。
匿名类型派生于Object,非匿名类型中的Equals、GetHashCode、ToString等方法,匿名类型也有。编译器重载了匿名类型的ToString方法,返回的类型的属性及对应的值,而不是类型名称。
参考:《编写高质量代码改善C#程序的157个建议》陆敏技