C#在2.0以后进入了一些新特性,如 自动属性,对象初始化器,集合初始化器和lambda表达式,另外还包括匿名方法、可空类型和扩展方法等。
详细见我2007年的文章,现测试几个初始化器在语法层面和reflector以后对比,可发现哪些是语法甜点,那些是CLR内置的改进。
1.自动属性:AutoProperty
直接给出类内属性field的名称,后面跟{},并在内部简单写get; set;即可。 编译器将自动创建私有属性字段,并实现get_属性名称和 set_属性名称method,属于编译器语法甜头。
public string FirstName{get;set;}
2.对象初始化器:Object Initilizer
简单讲就是可以在对象初始化的时候直接完成其属性的赋值。语法是在new 对象后紧跟{},并在{}内部设置属性的名称并赋值。
new Student{FirstName="Sophie", LastName="UX",Corperation="ibm"}
3.集合初始化器:Collection Initilizer
语法上在集合类型实例化语句New后面紧跟{},并在{}内填写元素.
double[] score = {98.5, 93.5, 99, 65.5}; float[] mesure = new float[]{98.5f, 93.5f, 99f, 65.5f};
4.lambda表达式: lambda expression
详细见下面的代码吧
using System;
using System.Linq;
using System.Collections.Generic;
public class Student
{ // auto property
public string FirstName{ get; set;}
public string LastName{ get; set;}
public string Corperation{ get; set;}
}
public class MyClass
{
public static void Main()
{ // List Generic
List<Student> students = new List<Student>{ // Collection Initializer
new Student{FirstName= " xu ", LastName= " Minghui ", Corperation= " LYPOWER "},
new Student{FirstName= " Sophie ", LastName= " UX ",Corperation= " ibm "},
new Student{FirstName= " xu ", LastName= " zisheng ", Corperation= " Home "}
// Object Initializer: give property value directly in a {} scope
};
var result1 = students.Where( p => p.FirstName.StartsWith( " xu ") );
var result2 = from stu in students where stu.FirstName.StartsWith( " xu ") select stu;
foreach( var v in result1)
Console.WriteLine( " {0} {1} work at {2}. ", v.FirstName, v.LastName, v.Corperation);
foreach( var v in result2)
Console.WriteLine( " {0} {1} work at {2}. ", v.FirstName, v.LastName, v.Corperation);
Console.ReadKey();
}
}
/*
public static void Main()
{
List<Student> list2 = new List<Student>();
Student item = new Student {
FirstName = "xu",
LastName = "Minghui",
Corperation = "LYPOWER"
};
list2.Add(item);
Student student3 = new Student {
FirstName = "Sophie",
LastName = "UX",
Corperation = "ibm"
};
list2.Add(student3);
Student student4 = new Student {
FirstName = "xu",
LastName = "zisheng",
Corperation = "Home"
};
list2.Add(student4);
List<Student> list = list2;
IEnumerable<Student> enumerable = from p in list
where p.FirstName.StartsWith("xu")
select p;
IEnumerable<Student> enumerable2 = from stu in list
where stu.FirstName.StartsWith("xu")
select stu;
foreach (Student student in enumerable)
{
Console.WriteLine("{0} {1} work at {2}.", student.FirstName, student.LastName, student.Corperation);
}
foreach (Student student in enumerable2)
{
Console.WriteLine("{0} {1} work at {2}.", student.FirstName, student.LastName, student.Corperation);
}
Console.ReadKey();
}
*/