在 C# 中,如何实现在自定义类中链接方法的能力,以便可以编写如下内容:
myclass.DoSomething().DosomethingElse(x);
etc...
Thanks!
链接是从现有实例生成新实例的一个很好的解决方案:
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);
您还可以使用此模式来修改现有实例,但通常不建议这样做:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)