【扩展】链式编程初识
/// <summary> /// 链式编程示例2 /// </summary> private static void Example2() { Person person = new Person { Name = "Tom" } .Run() .Sing() .Swim(); } 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; } }
这段代码定义了Peoson类,有三个操作Run、Swim、Sing,操作完成后返回自身this(有返回值是链式编程的关键)。返回自身this好比说执行完操作先别走人,还(可能)有其它操作要去做,如Example2中:先造一个People,先命令ta跑步,跑完先别休息再唱歌,再游泳,游泳完OK了。
链式编程是将多个操作(多行代码)通过点号"."链接在一起成为一句代码。(定义不严密,表达能力好的请给修正一下)
以下为常规代码与链式代码的比较:
/// <summary> /// 链式编程示例3 对比 /// </summary> private void Example3() { //链式代码 Person person = new Person { Name = "Tom" } .Run() .Sing() .Swim() .Run() .Sing() .Swim(); //常规代码 Person person2 = new Person(); person2.Run(); person2.Sing(); person2.Swim(); person2.Run(); person2.Sing(); person2.Swim(); }
为了增强效果,都执行了两轮操作。个人感觉链式代码更加精炼简洁易读。