質問

How and why does Braintree setup their API code this way? They are somehow allowing method calls that get chained and then populated into a variable that finally gets sent in through the Search() method. I've never seen APIs work this way before (except maybe Linq). How do they set this kind of thing up behind the scenes and what makes this better (or worse)?

https://www.braintreepayments.com/docs/dotnet/transactions/search

var request = new TransactionSearchRequest().
    CreditCardCardholderName.Is("Patrick Smith").
    CreditCardExpirationDate.Is("05/2012").
    CreditCardNumber.Is("5105105105105100");

ResourceCollection<Transaction> collection = gateway.Transaction.Search(request);
役に立ちましたか?

解決

If each method returns a reference to the object, you could chain as many together as you like.

public class Foo {
//  stuff...

    public Foo Baz() {
        // do stuff
        return this; //return a reference to the object
    }

}

I think the idea is (like linq), to have relational looking object oriented code.

Its kind of like defining a mini language within the API that follows its own rules, rather than the larger language conventions.

I prefer to hew closer to convention, but this sort of syntax is not unusual in the context of ORM's

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top