What fluent interfaces have you made or seen in C# that were very valuable? What was so great about them?

后端 未结 11 1197
-上瘾入骨i
-上瘾入骨i 2021-01-31 05:42

\"Fluent interfaces\" is a fairly hot topic these days. C# 3.0 has some nice features (particularly extension methods) that help you make them.

FYI, a fluent API means

11条回答
  •  清歌不尽
    2021-01-31 05:54

    This is actually the first time I've heard the term "fluent interface." But the two examples that come to mind are LINQ and immutable collections.

    Under the covers LINQ is a series of methods, most of which are extension methods, which take at least one IEnumerable and return another IEnumerable. This allows for very powerful method chaining

    var query = someCollection.Where(x => !x.IsBad).Select(x => x.Property1);
    

    Immutable types, and more specifically collections have a very similar pattern. Immutable Collections return a new collection for what would be normally a mutating operation. So building up a collection often turns into a series of chained method calls.

    var array = ImmutableCollection.Empty.Add(42).Add(13).Add(12);
    

提交回复
热议问题