如何实现方法链?

发布于 2024-08-17 12:13:06 字数 138 浏览 1 评论 0原文

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

myclass.DoSomething().DosomethingElse(x); 

等等...

谢谢!

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); 

etc...

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

影子是时光的心 2024-08-24 12:13:06

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

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);

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);
    }
}

Usage:

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;
    }
}

Usage:

MyInt x = new MyInt(10).Add(5).Subtract(7);
盛装女皇 2024-08-24 12:13:06

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

DoSomething should return a class instance with the DoSomethingElse method.

爱情眠于流年 2024-08-24 12:13:06

对于可变类,类似

class MyClass
{
    public MyClass DoSomething()
    {
       ....
       return this;
    }
}

For a mutable class, something like

class MyClass
{
    public MyClass DoSomething()
    {
       ....
       return this;
    }
}
入画浅相思 2024-08-24 12:13:06

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

Your methods should return this or a reference to another (possibly new) object depending on exactly what you want to acheive

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文