在 C# 中,如何实现在自定义类中链接方法的能力,以便可以编写如下内容:
myclass.DoSomething().DosomethingElse(x);
ETC...
谢谢!
链接是从现有实例生成新实例的一个很好的解决方案:
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
或引用另一个(可能是新的)对象,具体取决于您想要实现的目标