如何实现方法链接?

Ton*_*ion 6 c# methods chaining

在C#中,如何实现在一个自定义类中链接方法的能力,以便可以编写如下内容:

myclass.DoSomething().DosomethingElse(x); 
Run Code Online (Sandbox Code Playgroud)

等等...

谢谢!

dtb*_*dtb 14

链接是从现有实例生成新实例的好方法:

public class MyInt
{
    private readonly int value;

    public MyInt(int value) {
        this.value = value;
    }
    public MyInt Add(int x) {
        return new MyInt(this.value + x);
    }
    public MyInt Subtract(int x) {
        return new MyInt(this.value - x);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

MyInt x = new MyInt(10).Add(5).Subtract(7);
Run Code Online (Sandbox Code Playgroud)

您也可以使用此模式修改现有实例,但通常不建议这样做:

public class MyInt
{
    private int value;

    public MyInt(int value) {
        this.value = value;
    }
    public MyInt Add(int x) {
        this.value += x;
        return this;
    }
    public MyInt Subtract(int x) {
        this.value -= x;
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

MyInt x = new MyInt(10).Add(5).Subtract(7);
Run Code Online (Sandbox Code Playgroud)