方式1:
定义方法时,将方法的返回值设置为其本身类
public class Test
{
public Test A1()
{
Console.WriteLine("A1");
return this;
}
public Test A2()
{
Console.WriteLine("A2");
return this;
}
public Test A3()
{
Console.WriteLine("A3");
return this;
}
}
方法2
正常定义方法,并使用扩展方法将需要链式调用的方法类进行扩展
public class Test
{
public void A1()
{
Console.WriteLine("A1");
}
public void A2()
{
Console.WriteLine("A2");
}
public void A3()
{
Console.WriteLine("A3");
}
}
public static class Expand
{
public static Test Do(this Test t, Action<Test> action)
{
action(t);
return t;
}
}
或者使用泛型扩展
public static class Expand
{
public static T Do<T>(this T t, Action<T> action)
{
action(t);
return t;
}
}
方法1调用:
new Test()
.A1()
.A2()
.A3();
方法2调用:
new Test()
.Do(s => s.A1())
.Do(s => s.A2())
.Do(s => s.A3());