Generic 'TThis' for fluent classes

后端 未结 1 1600
盖世英雄少女心
盖世英雄少女心 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<T,TThis> 
        where TThis : FieldBase<T,TThis>
    {
        private string _name;
        public TThis Name( string name ) 
        {
            _name = name;
            return (TThis)this;
        }
    }
    
    public class Field<T> : FieldBase<T,Field<T>>{}
    
    public class SpecialFieldBase<T,TThis> : FieldBase<T,TThis>
        where TThis : SpecialFieldBase<T,TThis>
    {
        public TThis Special(){ return (TThis)this; }
    }
    
    public class SpecialField<T> : SpecialFieldBase<T,SpecialField<T>>{}
    
    
    // Yeah it works!
    var specialField = new SpecialField<string>()
        .Name( "bing" )
        .Special();
    
    0 讨论(0)
提交回复
热议问题