Fluent interfaces and inheritance in C#

后端 未结 7 1733
野性不改
野性不改 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:59

    Is a fluent interface really the best call here, or would an initializer be better?

     var p = new Person{
          LastName = "Smith",
          FirstName = "John"
          };
    
     var c = new Customer{
          LastName = "Smith",
          FirstName = "John",
          AccountNumber = "000",
          ID = "123"
          };
    

    Unlike a fluent interface, this works fine without inherited methods giving back the base class and messing up the chain. When you inherit a property, the caller really shouldn't care whether FirstName was first implemented in Person or Customer or Object.

    I find this more readable as well, whether on one line or multiple, and you don't have to go through the trouble of providing fluent self-decorating functions that correspond with each property.

提交回复
热议问题