流畅的API和方法链接样式用法 [英] Fluent API and Method-Chaining Style Usage

查看:161
本文介绍了流畅的API和方法链接样式用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用流畅的API或仅使用方法链接进行编程时,我看到的样式大致如下:

When programming against a fluent API or just using method-chaining, I've seen the style mostly like this:

var obj = objectFactory.CreateObject()
    .SetObjectParameter(paramName, value)
    .SetObjectParameter(paramName, value)
    .DoSomeTransformation();

将点放在行的开头而不是行的末尾像这样:

What is the reasoning behind putting the dot at the beginning of the line instead of the end of the line like this:

var obj = objectFactory.CreateObject().
    SetObjectParameter(paramName, value).
    SetObjectParameter(paramName, value).
    DoSomeTransformation();

或者,这只是一个团队在一个共识的风格的事情吗?

Or, is it merely a style thing that a team makes a consensus on?

推荐答案

这只是一个风格的东西。

It's merely a style thing.

在行的开头是,它使它更清楚地快速浏览,这不是一个独立的方法调用。

The advantage of putting the . at the beginning of the line is that it makes it more clear on a quick glance that this isn't a standalone method call.

例如,如果你这样做: / p>

For example, if you do:

var obj = objectFactory.CreateObject()
    .SetObjectParameter(paramName, value)

你可以告诉 SetObjectParameter(...)一些其他对象,只是看着那条线。这样做:

You can tell that SetObjectParameter(...) is a method being called on some other object, just looking at that line. Doing this:

var obj = objectFactory.CreateObject().
    SetObjectParameter(paramName, value)

需要查看上一行才能知道。例如,这可能是一个格式化问题,即:

Requires you to look at the previous line to tell. For example, this could be a formatting problem, ie:

var obj = objectFactory.CreateObject();
    SetObjectParameter(paramName, value);

(这里, SetObjectParameter 对当前类型,而不是由 CreateObject()返回的类型 - 但是,通过查看第二行,这不是明显的没有。开始那一行)。

(Here, SetObjectParameter would be a method on the current type, not on the type returned by CreateObject() - but, by looking at the second line, this is not apparent without the . beginning that line).

这篇关于流畅的API和方法链接样式用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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