• 隐式类型的本地变量和数组
var i = 5;
var a = new[] { 0, 1, 2 };
• 对象初始值设定项
private class Cat
{
public int Age { get; set; }
public string Name { get; set; }
}
static void MethodA()
{
Cat cat = new Cat { Age = 10, Name = "Sylvester" }; {g , y };
}
• 集合初始值设定项
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> digits2 = new List<int> { 0 + 1, 12 % 3, MakeInt() };
• 自动实现的属性
class LightweightCustomer
{
public double TotalPurchases { get; set; }
public string Name { get; private set; } // read-only
public int CustomerID { get; private set; } // read-only
}
• 匿名类型
var v = new { Amount = 108, Message = "Hello" };
• 扩展方法
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}using ExtensionMethods;
string s = "Hello Extension Methods";
int i = s.WordCount();
• 分部方法定义
// Definition in file1.cs
partial void onNameChanged();
// Implementation in file2.cs
partial void onNameChanged()
{
// method body // et od body
}
• Lambda 表达式
Lambda 表达式
var results = people.Where(p => p.LastName == "White");
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
Lambda 语句
delegate void TestDelegate(string s);
… …
TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
myDel("Hello");