[英]How to implement method chaining?
在C#中,如何实现在一个自定义类中链接方法的能力,以便可以编写如下内容:
myclass.DoSomething().DosomethingElse(x);
等等...
谢谢!
链接是从现有实例生成新实例的好方法:
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);
DoSomething应该使用DoSomethingElse方法返回一个类实例。
对于一个可变类,类似于
class MyClass
{
public MyClass DoSomething()
{
....
return this;
}
}
您的方法应该返回this
或对另一个(可能是新的)对象的引用,具体取决于您想要实现的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.