9

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

myclass.DoSomething().DosomethingElse(x); 

ETC...

谢谢!

4

4 回答 4

16

链接是从现有实例生成新实例的一个很好的解决方案:

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);
于 2010-01-13T09:46:20.900 回答
1

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

于 2010-01-13T09:42:31.560 回答
1

对于可变类,例如

class MyClass
{
    public MyClass DoSomething()
    {
       ....
       return this;
    }
}
于 2010-01-13T09:44:55.067 回答
0

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

于 2010-01-13T09:48:03.303 回答