何时在方法中返回“this”而不是“void”,为什么?

问题描述 投票:0回答:1

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

在CodeReview.StackExchange上查看答案时,我注意到答案在自操作方法中使用了“返回此”。

原始类的简化:

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

一个相关的问题,返回这个而不是void有什么缺点吗?,不同用户的答案似乎有冲突。

void方法和return this有什么区别也类似,答案引用了在对象创建中使用的流畅接口。

c# oop method-chaining fluent-interface
1个回答
8
投票

返回

this
使用流畅的接口设计,这是方法链接的特殊情况,当返回类型是我们正在应用该方法的当前对象时。

方法链也是函数式编程的根源。

它被带有 IEnumerable<>

IQueryable<>
Linq
扩展方法广泛使用。

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

因此,这会产生更短、更干净、更易于维护的代码,并且错误源更少。

因此,当我们想要或需要时,我们就使用它。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.