1

C# にコレクション初期化子があり、コンストラクターを呼び出さずにクラスのプロパティを定義できる場合、C# でメソッド チェーンを使用する意味はありますか? 何も見えません。多分私はここで何かを逃していますか?

ありがとう

4

3 に答える 3

8

リンク?

var item = sequence.Where(x => x.Age > 100)
                   .Select(x => new { x.FirstName, x.LastName })
                   .OrderBy(x => x.LastName)
                   .FirstOrDefault();
于 2010-05-21T16:24:00.277 に答える
6

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.

于 2010-05-21T16:14:42.123 に答える
4

CuttingEdge.Conditionsは、メソッド チェーンが便利な理由を示す良い例ですか?

public void GetData(int? id)
{
    // Check all preconditions:
    Condition.Requires(id)
        .IsNotNull()
        .IsInRange(1, 999)
        .IsNotEqualTo(128);
}
于 2010-05-21T16:50:03.193 に答える