如何实现方法链接? [英] How to implement method chaining?
本文介绍了如何实现方法链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,一个人如何实现在自己的自定义类中链接方法的功能,以便可以编写如下内容:
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);
等...
谢谢!
推荐答案
链式是从现有实例中生成新实例的好方法:
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);
}
}
用法:
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;
}
}
用法:
MyInt x = new MyInt(10).Add(5).Subtract(7);
这篇关于如何实现方法链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文