简体   繁体   中英

How to add a value to a context with callbacks following Fluent Builder pattern

I'm using Fluent Builder with callbacks to configure a context on the fly.

Currently, I have a PlaneContext class with a list of passengers which I want to populate by using the method AddPassenger like:

var builder = new PlaneBuilder<PlaneContext>();

builder.AddPlane(plane => plane.Name = "Boeng") 
    .AddPassenger(passenger => passenger.Name = "Robert")
    .AddPassenger(passenger => passenger.Name = "Johnny");

As shown above, I've created a PlaneBuilder class to chain methods like these. The first method AddPlane works fine, but the chained methods AddPassenger does not work as expected. My lack of understanding in delegates as Action<T> and Func<T, TResult> is highly the issue.

This is what I have tried, but I get cannot implicitly convert string to Passenger :

public PlaneBuilder<T> AddPassenger(Func<Passenger, Passenger> callback)
{
    var passenger = callback(new Passenger());
    _planeContext.Passengers.Add(passenger);
    return this;
}

Currently, this is how the PlaneBuilder class looks like:

class PlaneBuilder<T>
{

    private PlaneContext _planeContext = new PlaneContext();

    public PlaneBuilder<T> AddPlane(Action<PlaneContext> callback)
    {
        callback(_planeContext);
        return this;
    }

    public PlaneBuilder<T> AddPassenger(Func<Passenger, Passenger> callback)
    {
        // Goal is to create a passenger
        // Add it to the passengers list in PlaneContext
        var passenger = callback(new Passenger());
        _planeContext.Passengers.Add(passenger);
        return this;
    }
}

Lastly, here's the PlaneContext class:

class PlaneContext
{
    public string Name { get; set; }
    public string Model { get; set; }
    public List<Passenger> Passengers { get; set; }
}

In short, how can I add passenger to PlaneContext using callbacks?

The is a solution to my problem as described above:

First, the list must be initialized in PlaneContext class like:

public List<Passenger> Passengers = new List<Passenger>();

Secondly, in order to add a passenger to Passengers list: create a new instance of Passenger class, pass it as an argument to the callback method, and then add it to the passengers list like:

public PlaneBuilder<T> AddPassenger(Action<Passenger> callback)
{
    var passenger = new Passenger();
    callback(passenger);
    _planeContext.Passengers.Add(passenger);
    return this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM