【问题标题】:How to implement method chaining?如何实现方法链?
【发布时间】:2010-01-13 09:40:45
【问题描述】:

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

myclass.DoSomething().DosomethingElse(x); 

等等……

谢谢!

【问题讨论】:

标签: c# methods chaining


【解决方案1】:

链式是从现有实例生成新实例的好方法:

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

【讨论】:

  • +1 就是一个很好的例子。通常,这个概念被称为 Fluent Interface - 请参阅en.wikipedia.org/wiki/Fluent_interface。虽然从技术上讲你没有使用一个,但引入一个是微不足道的。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    对于可变类,类似

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-15
        • 2014-02-06
        • 2021-05-27
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 2014-10-17
        • 1970-01-01
        相关资源
        最近更新 更多