如何实现方法链接?

时间:2010-01-13 09:40:46

标签: c# methods chaining

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

myclass.DoSomething().DosomethingElse(x); 

等...

谢谢!

4 个答案:

答案 0 :(得分:12)

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

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);
    }
}

用法:

MyInt x = new MyInt(10).Add(5).Subtract(7);

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

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;
    }
}

用法:

MyInt x = new MyInt(10).Add(5).Subtract(7);

答案 1 :(得分:1)

DoSomething应该使用DoSomethingElse方法返回一个类实例。

答案 2 :(得分:1)

对于可变类,类似

class MyClass
{
    public MyClass DoSomething()
    {
       ....
       return this;
    }
}

答案 3 :(得分:0)

您的方法应该返回this或引用另一个(可能是新的)对象,具体取决于您想要实现的目标