【发布时间】: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方法,它需要一个容器左右。 -
这种模式通常被称为
fluentapi。
标签: c# oop method-chaining fluent-interface