在修改自身的方法中返回对“this”对象的引用有什么好处(或缺点)?什么时候应该使用返回“this”而不是 void?
当查看代码审查堆栈交换的答案时,我注意到答案在自操作方法中使用了“返回此”。
原始类的简化:
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>();
}
Run Code Online (Sandbox Code Playgroud)
使用代码简化:
var fireSword = new Item("Lightbringer")
.AddComponent(new Valuable { Cost = 1000 })
.AddComponent(new PhysicalDamage { Slashing = 10 });
Run Code Online (Sandbox Code Playgroud)
相关问题似乎不同用户的答案相互矛盾。
这个问题也与引用在对象创建中使用的流畅接口的答案类似。