Lambda 表达式:
Func<string, string> doubleAppend= x => x + x;
Console.WriteLine (doubleAppend(“test”)); // testtest
LINQ 查询:
string[] names = { "Tom", "Dick", "Harry" };
IEnumerable<string> filteredNames =
Enumerable.Where (names, n => n.Length >= 4); // 字符长度大于等于4的名字
扩展方法:
string[] names = { "Tom", "Dick", "Harry" };
IEnumerable<string> filteredNames = names.Where (n => n.Length >= 4);
隐式类型的局部变量:
var filteredNames = names.Where (n => n.Length == 4);
查询理解语法:
var filteredNames = from n in names where n.Length >= 4 select n;
匿名类型:
var query = from n in names where n.Length >= 4
select new {
Name = n,
Length = n.Length
};
var dude = new { Name = "Bob", Age = 20 };
隐藏类型的数组:
var dudes = new[]
{
new { Name = "Bob", Age = 20 },
new { Name = "Rob", Age = 30 }
};
对象初始化:
class Bunny
{
public string Name;
public bool LikesCarrots;
public bool LikesHumans;
}
// C# 3.0
Bunny b1 = new Bunny { Name="Bo", LikesCarrots=true, LikesHumans=false }; // C# 2.0
Bunny b2 = new Bunny();
b2.Name = "Bo";
b2.LikesHumans = false;
自动的属性:
public class Stock
{
// C# 3.0:
public decimal X { get; set; } // C# 2.0:
private decimal y;
public decimal Y
{
get { return y; }
set { y = value; }
}
}
Partial 方法:
// PaymentFormGen.cs — auto-generated
partial class PaymentForm
{
...
partial void ValidatePayment (decimal amount);
} // PaymentForm.cs — hand-authored
partial class PaymentForm
{
...
partial void ValidatePayment (decimal amount)
{
if (amount > 100)
...
}
}
表达式树:
Expression<Func<string, bool>> predicate = s => s.Length > 10;
Func<string, bool> fun = predicate.Compile();
Console.WriteLine(fun("test").ToString());