Method chaining without parentheses, how to?

本小妞迷上赌 提交于 2019-12-08 05:09:29
Dethariel

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.

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