lundi 19 juin 2017

Returning calling child instance from interface or class

So this question is a clear case of one stone kills two birds (a design and code question) I have a base class which has a base interface

interface IBase
{
   IBase Method1();
}

class Base : IBase
{
   IBase Method1()
   {
     //do work
     return this;
   }
}

Now the child class

interface IChild1 : IBase
{
  IChild1 ChildMethod();
}

class Child1 : Base, IChild1
{
  public IChild1 ChildMethod()
  {
    //do work 
    // this would work fine Method1(); ChildMethod2();
    //but I want to chain methods
    Method1().ChildMethod2();
    return this;
  }

  void ChildMethod2()
  {
    //do work
  }
}

The crux of the matter is I want the base class to return the child class instance. As you can tell from the code in the method ChildMethod(), the base class method Method1() returns the instance of IBase so chaining ChildMethod2() would not be possible. Yes I could live without having to chain the method, but lets assume that is my only option.

Here is my attempt at using generics

interface IBase<T> where T : IBase<T>
{
    T Method1();
}

class Base<T> : IBase<T> where T : Base<T>
{
    public T Method1()
    {
        //do work
        return (T)this;
    }
}

interface IChild1 : IBase<IChild1>
{
    IChild1 ChildMethod();
}

class Child1 : Base<Child1>, IChild1
{
    public IChild1 ChildMethod()
    {
        //do work
        Method1(); ChildMethod2();
        return this;
    }

    void ChildMethod2()
    {
        //do work
    }        
}

To put things clearly what I am trying to achieve is that for each call I make to the base class (interface in this case) I want the calling class/interface returned. Note: Using Autofac for dependency injection

Aucun commentaire:

Enregistrer un commentaire