About chain calls

    • for example

Method chaining (method chaining) is a common syntax in object-oriented programming languages, which allows developers to make multiple method calls to the same object while only referencing the object once. Although chained calls are not included in the 23 design patterns, it is a commonly used code design method.

Extension methods enable you to "add" methods to an existing type without having to create a new derived type, recompile, or otherwise modify the original type. An extension method is a static method, but can be called like an instance method on an extension type.

When writing code, using chain calls can make the behavior of the code clearer, while extension methods can add behaviors to types without modifying the original types (including built-in types such as int and string).

For example, add methods to C#'s int and string types:

using System;

using System.Text;

namespace ExampleProject

{

class Program

{

static void Main(string[] arg)

{

int num = 1.Plus(40)

.Plus(9)

.Subtract(2)

.Multi(10)

.Divide(2);

string str = "Hello World!".Add(" This is C#.")

.Remove(" World");

Console.WriteLine(num);

Console.WriteLine(str);

}

}

///<summary>

///Extension method of int type

///</summary>

public static class class1

{

public static int Plus(this int num1,int num2)

{

return num1+num2;

}

public static int Subtract(this int num1,int num2)

{

return num1-num2;

}

public static int Multi(this int num1,int num2)

{

return num1*num2;

}

public static int Divide(this int num1,int num2)

{

return num1/num2;

}

}

///<summary>

///Extension method of string type

///</summary>

public static class class2

{

public static string Add(this string str1,string str2)

{

return str1+str2;

}

public static string Remove(this string str1,string str2)

{

string[] strs = str1.Split(new string[]{str2},StringSplitOptions.RemoveEmptyEntries);

str1 = "";

foreach (var item in strs)

{

str1+=item;

}

return str1;

}

}

}

//Output:

//240

//Hello! This is C#.

    • Write a code and view it together

/// <summary>

/// Chain programming example in EntityFramwork

/// </summary>

private void Example1()

{

using (NorthwindEFEntities northwindEFEntities = new NorthwindEFEntities())

{

northwindEFEntities.Employees

.Where(e => e.FirstName.StartsWith("C"))

.Select(e => e.FirstName)

.OrderBy(s => s);

}

}

This basic query performs three operations: 1. Find employees whose FristName starts with C; 2. Get the employee's FirstName; 3. Sort the names.

    • Only one statement is needed in EF, and the three are chained into one statement through . More statements can be linked later.

The following code has some evolution:

/// <summary>

/// Chain programming example 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;

}

}

This code defines the Peoson class, which has three operations: Run, Swim, and Sing. After the operation is completed, it returns itself this (having a return value is the key to chain programming). Returning this to itself is like saying don't leave after executing the operation. There are (maybe) other operations to be done, such as in Example 2: first create a People, first order them to run, don't rest before singing, then swim, swim OK.

Chain programming is to link multiple operations (multiple lines of code) together through the period "." into one sentence of code. (The definition is not strict, please correct it if you are good at expressing yourself)

    • Here's a comparison of regular code and chaincode:

/// <summary>

/// Chain programming example 3 comparison

/// </summary>

private void Example3()

{

//chain code

Person person = new Person { Name = "Tom" }

.Run()

.Sing()

.Swim()

.Run()

.Sing()

.Swim();

//Regular code

Person person2 = new Person();

person2.Run();

person2.Sing();

person2.Swim();

person2.Run();

person2.Sing();

person2.Swim();

}

为了增强效果,都执行了两轮操作。个人感觉链式代码更加精炼简洁易读。

链式代码要求操作有返回值,但对于很多操作大都是void型,什么也不返回,这样就很难链起来了。当然也有解决办法,可能不太优雅。

    • 使用扩展方法解决这个问题,首先引入一个泛型扩展:

/// <summary>

/// 先执行操作,再返回自身

/// </summary>

public static T Do<T>(this T t, Action<T> action)

{

action(t);

return t;

}

下面是调用示例,其中Student类操作都是void型的。

/// <summary>

/// 链式编程示例4

/// </summary>

private static void Example4()

{

new Student { Name = "Tom" }

.Do(s => s.Run())

.Do(s => s.Sing())

.Do(s => s.Sing())

.Do(s => s.Name = "Bob");

}

public class Student

{

public string Name { get; set; }

public void Run() { Console.WriteLine("Run"); }

public void Swim() { Console.WriteLine("Swim"); }

public void Sing() { Console.WriteLine("Sing"); }

}

Guess you like

Origin blog.csdn.net/2201_75837601/article/details/128637378