1

How to invoke function Run() from Controller class in class I2C?

class Program
{
    public class Controller
    {
        public void Run()
        {
        }
    }

    public class ChildController : Controller
    {
    }

    public class LowLevelController : ChildController
    {
        private class I2C
        {
            public I2C()
            {
            }

            // Want to call Controller.Run() from this level
        }

        public void Computate()
        {
            base.Run();
        }
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 2
    `instanceOfController.Run()` – user4003407 Jul 27 '19 at 13:05
  • You should read about Object oriented programming – ilansch Jul 27 '19 at 13:11
  • This is basically a dupe of https://stackoverflow.com/questions/185124/whats-the-best-way-of-accessing-field-in-the-enclosing-class-from-the-nested-cl – StayOnTarget Jul 27 '19 at 13:35
  • Possible duplicate of [What's the best way of accessing field in the enclosing class from the nested class?](https://stackoverflow.com/questions/185124/whats-the-best-way-of-accessing-field-in-the-enclosing-class-from-the-nested-cl) – StayOnTarget Jul 27 '19 at 13:35

2 Answers2

2

Option 1

One way to achieve this would be exposing method in I2C which accepts an Action. This would allow the instance of I2C, which is a private class defined within LowLevelController to invoke Controller.Run. For example,

 private class I2C
 {
     public I2C()
     {
     }

     public void RunBase(Action execute)
     {
        execute.Invoke();
     }
 }

Now you could execute the RunBase as

 public void Computate()
 {
    var i2c = new I2C();
    i2c.RunBase(()=>base.Run());
 }

Option 2

The other option would be to pass an instance of LowLevelController to I2C and invoke the Controller.Run method

Example,

public class LowLevelController : ChildController
{
    private class I2C
    {
       private LowLevelController _parent;
       public I2C(LowLevelController parent)
       {
          _parent = parent;
       }

       public void RunBase()
       {
          _parent.Run();
       }
    }

     public void Computate()
     {
         var i2c = new I2C(this);
         i2c.RunBase();
     }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
0

I think what you want is simply:

public class LowLevelController : ChildController {

    private class I2C {

        public I2C(LowLevelController outerInstance) {
            OuterInstance = outerInstance;
        }

        private LowLevelController OuterInstance { get; }

        private void DoSomething() {
            OuterInstance.Run();
        }

    }

}
Christoph
  • 3,322
  • 2
  • 19
  • 28