Fluent interfaces and inheritance in C#

后端 未结 7 1745
野性不改
野性不改 2020-11-30 21:09

I\'ll show a problem by example. There is a base class with fluent interface:

class FluentPerson
{
    private string _FirstName = String.Empty;
    private          


        
7条回答
  •  野性不改
    2020-11-30 21:54

    You can use generics to achieve that.

    public class FluentPerson
        where T : FluentPerson
    {
        public T WithFirstName(string firstName)
        {
            // ...
            return (T)this;
        }
    
        public T WithLastName(string lastName)
        {
            // ...
            return (T)this;
        }
    }
    
    public class FluentCustomer : FluentPerson
    {
        public FluentCustomer WithAccountNumber(string accountNumber)
        {
            // ...
            return this;
        }
    }
    

    And now:

    var customer = new FluentCustomer()
      .WithAccountNumber("123")
      .WithFirstName("Abc")
      .WithLastName("Def")
      .ToString();
    

提交回复
热议问题