Can somehow a method from base class return child class?

前端 未结 2 1745
遥遥无期
遥遥无期 2021-01-02 13:19

I\'ll give an example, so you can better understand what i mean:

public class Base
{
      public Base Common()
      {
          return this;
      }
}

pub         


        
相关标签:
2条回答
  • 2021-01-02 13:59

    You could make Base generic and use the Curiously Repeating Template Pattern:

    public class Base<T> where T : Base<T>
    {
          public T Common()
          {
              return (T)this;
          }
    }
    
    public class XBase : Base<XBase>
    {
         public XBase XMethod()
         {
              return this;
         }
    }
    

    Then you can just use:

    var a = new XBase().Common().XMethod();
    
    0 讨论(0)
  • 2021-01-02 14:04

    Have Base be abstract and not implementing XMethod and have the classes overriding XMethod should do it I guess?

    public abstract class Base<T>
    {
          public Base Common()
          {
              return this;
          }
    
         public abstract T XMethod();
    }
    
    public class XBase : Base<XBase>
    {
    
         public override XBase XMethod()
         {
              return this;
         }
    }
    
    0 讨论(0)
提交回复
热议问题