How to implement method chaining?

旧巷老猫 提交于 2020-01-01 09:18:30

问题


In C# how does one implement the ability to chain methods in one's custom classes so one can write something like this:

myclass.DoSomething().DosomethingElse(x); 

etc...

Thanks!


回答1:


Chaining is a good solution to produce new instance from existing instances:

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

Usage:

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

You can also use this pattern to modify an existing instance, but this is generally not recommended:

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

Usage:

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



回答2:


DoSomething should return a class instance with the DoSomethingElse method.




回答3:


For a mutable class, something like

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



回答4:


Your methods should return this or a reference to another (possibly new) object depending on exactly what you want to acheive



来源:https://stackoverflow.com/questions/2055667/how-to-implement-method-chaining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!