Is it worth to use method chaining in C#?

我怕爱的太早我们不能终老 提交于 2019-12-08 05:13:41

问题


Having Collection initializers in C# and being allowed to define properties of a class without having to call the constructor, is there any point in using Method Chaining in C#? I can't see any. Maybe I'm missing something here?

Thanks


回答1:


LINQ?

var item = sequence.Where(x => x.Age > 100)
                   .Select(x => new { x.FirstName, x.LastName })
                   .OrderBy(x => x.LastName)
                   .FirstOrDefault();



回答2:


A common use is fluent interfaces

EDIT: In response to the questions in the comments, property/collection initialisers are fairly limited in that you can only set propeties or call the Add method on a collection, whereas method calls are more flexible since they can take multple arguments.

A fluent interface is just one specific use of method chaining to produce a more readable API, often for object builders.

Also, as an aside that MSDN article is quite misleading since object initialisers don't allow you to bypass the constructor, it's just that in the example, the StudentName class has a default constructor which does nothing.




回答3:


CuttingEdge.Conditions is a good example of why method chaining is convenient?

public void GetData(int? id)
{
    // Check all preconditions:
    Condition.Requires(id)
        .IsNotNull()
        .IsInRange(1, 999)
        .IsNotEqualTo(128);
}


来源:https://stackoverflow.com/questions/2883679/is-it-worth-to-use-method-chaining-in-c

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