1.用处
链式编程能够将多个操作或者多行代码通过点号(.)链接在一起,方便修改和阅读。
诸如C#中的的Linkq语法
private void Example1()
{
using (NorthwindEFEntities northwindEFEntities = new NorthwindEFEntities())
{
northwindEFEntities.Employees
.Where(e => e.FirstName.StartsWith("C"))
.Select(e => e.FirstName)
.OrderBy(s => s);
}
}
这一个基本的查询,执行了三个操作:1.查找FristName以C开头的员工;2.取员工的FirstName;3.将名字排序。
2.使用示例
private static void Example2()
{
//链式代码
Person person = new Person { Name = "Tom" }
.Run()
.Sing()
.Swim()
.End();
//常规代码
Person person2 = new Person();
person2.Run();
person2.Sing();
person2.Swim();
person2.End();
}
class Person
{
public string Name { get; set; }
public Person Run()
{
Console.WriteLine("Run");
return this;
}
public Person Swim()
{
Console.WriteLine("Swim");
return this;
}
public Person Sing()
{
Console.WriteLine("Sing");
return this;
}
//完成,此处返回值为void,这样的话这个方法只能位于最后,这个方法之后无法再点出其他方法
public void End()
{
Console.WriteLine("End");
}
}