何时在方法中返回“this"而不是“void",为什么? [英] When to return 'this' instead of 'void' in a method and why?

查看:55
本文介绍了何时在方法中返回“this"而不是“void",为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在修改自身的方法中返回对this"对象的引用有什么好处(或缺点)?什么时候应该返回一个 'this' 与 void 关联?

What are the benefits (or drawbacks) of returning a reference to 'this' object in a method that modifies itself? When should returning a 'this' be used as apposed to void?

在查看 关于代码审查堆栈交换的答案时,我注意到答案使用了返回这个' 在自操作方法中.

When looking at an answer on code review stack exchange, I noticed that the answer used a 'return this' in a self operating method.

原始类的简化类:

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 seems to have conflicting answers by different users.

这个问题也类似答案引用了用于创建对象的流畅接口.

This question is also similar with the answer referencing fluent interfaces to use in object creation.

推荐答案

返回 this 正在使用 流畅的界面设计,这是方法链 当返回类型是我们正在应用该方法的当前对象时.

Returning this is using a fluent interface design, that is a special case of method chaining when the return type is of the current object on which we are applying the method.

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

它被 Linq 扩展方法广泛使用,包括 IEnumerable<>IQueryable<>.

It is extensively used by Linq extension methods with IEnumerable<> and IQueryable<>.

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

It allows to call methods on the same object in a chained manner without repeating a variable name for each method call.

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

Therefore, this produces a shorter, cleaner and more maintainable code with fewer sources of errors.

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

So we use this when we want or need that.

这篇关于何时在方法中返回“this"而不是“void",为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆