如何实现方法链?

9

在C#中,如何实现自定义类中的方法链式调用?这样可以编写类似于以下代码:

myclass.DoSomething().DosomethingElse(x); 

etc...

Thanks!


请看 https://dev59.com/LHNA5IYBdhLWcg3wBpHs - Randy Levy
4个回答

17

链式调用是一种从现有实例产生新实例的好方法:

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
对于这个好的例子点赞。通常这个概念被称为流畅接口 - 参见http://en.wikipedia.org/wiki/Fluent_interface。虽然严格来说你没有使用它,但引入一个是微不足道的。 - Wim

1
对于可变类,类似以下代码:
class MyClass
{
    public MyClass DoSomething()
    {
       ....
       return this;
    }
}

1

DoSomething应该返回一个具有DoSomethingElse方法的类实例。


0

你的方法应该根据你想要实现的目标,返回this或另一个(可能是新的)对象的引用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接