Method chaining without parentheses, how to?

牧云@^-^@ 提交于 2019-12-23 04:12:25

问题


I would like to do a method chain, for example like this:

Car myCar = new Car();

// Chaining
myCar.config.engine.cylinders("4");

But how do I do the chaining, without using parentheses in "config" or "engine"?

I can only figure out to do it like this:

myCar.config().engine().cylinders("4");

回答1:


You can do this by declaring Config property in your Car class. Then Engine property in CarConfig class, like this:

public class Car
{
    public CarConfig Config { get; set; }
}

Then you can chain the calls.




回答2:


You could use properties as many suggest, but this whole thing stinks of breaking the Law of Demeter (or Principle of Least Knowledge). Basically you are breaking the encapsulation of the Car class. You may want to take a look at Builder Pattern, especially the fluent implementations (like here).

Your code may then look like

Car myCar = new CarBuilder().WithEngineCylinders("4");


来源:https://stackoverflow.com/questions/20242737/method-chaining-without-parentheses-how-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!