【问题标题】:When to return 'this' instead of 'void' in a method and why?何时在方法中返回“this”而不是“void”,为什么?
【发布时间】:2020-12-06 21:18:50
【问题描述】:

在修改自身的方法中返回对“this”对象的引用有什么好处(或缺点)?什么时候应该将返回的“this”与 void 相对应?

查看answer on code review stack exchange 时,我注意到答案在自我操作方法中使用了“return this”。

原始类的简化:

class Item
{
    public Item(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }

    public Item AddComponent(ItemComponent component)
    {
        _components.Add(component);
        return this;
    }

    private List<ItemComponent> _components = new List<ItemComponent>();
}

消费代码简化:

var fireSword = new Item("Lightbringer")
                   .AddComponent(new Valuable { Cost = 1000 })
                   .AddComponent(new PhysicalDamage { Slashing = 10 });

Related question 似乎有不同用户的相互矛盾的答案。

This question 也与引用流畅接口以用于对象创建的答案类似。

【问题讨论】:

  • 因为您可以链接方法调用。仅为方便起见......在示例中会有另一种解决方案,例如一个AddMany 方法,它需要一个容器左右。
  • 这种模式通常被称为fluent api。

标签: c# oop method-chaining fluent-interface


【解决方案1】:

返回this 使用fluent interface 设计,这是method chaining 的特例,当返回类型是我们正在应用该方法的当前对象时。

方法链也是functional programming的根源。

它被IEnumerable&lt;&gt;IQueryable&lt;&gt;Linq 扩展方法广泛使用。

它允许以链式方式调用同一对象上的方法,而无需为每个方法调用重复一个变量名。

因此,这会生成更短、更简洁、更易于维护的代码,并且错误源更少。

所以我们在需要或需要时使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2022-01-22
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多