Generic 'TThis' for fluent classes

后端 未结 1 1599
盖世英雄少女心
盖世英雄少女心 2021-02-08 02:08

I\'m constructing a fluent interface where I have a base class that contains the bulk of the fluent logic, and a derived class that add some specialized behavior. The problem I\

1条回答
  •  伪装坚强ぢ
    2021-02-08 02:57

    After poking around some other fluent APIs I found how to do it. It's not quite as clean, but it works well. Basically you introduce an intermediary base class for each derived type that you want to use and it passes the "TThis" type to the actual implementation.

    Sample

    public class FieldBase 
        where TThis : FieldBase
    {
        private string _name;
        public TThis Name( string name ) 
        {
            _name = name;
            return (TThis)this;
        }
    }
    
    public class Field : FieldBase>{}
    
    public class SpecialFieldBase : FieldBase
        where TThis : SpecialFieldBase
    {
        public TThis Special(){ return (TThis)this; }
    }
    
    public class SpecialField : SpecialFieldBase>{}
    
    
    // Yeah it works!
    var specialField = new SpecialField()
        .Name( "bing" )
        .Special();
    

    0 讨论(0)
提交回复
热议问题