开发者

Nested C# Classes - Calling Outer Method From Inner

开发者 https://www.devze.com 2022-12-10 18:47 出处:网络
I have a ViewController class called GamePlay.In GamePlay there is a nested class called MyPinAnnotationView.When MyPinAnnotation\'s method TouchesBegan() gets called, I want to call a method CheckAns

I have a ViewController class called GamePlay. In GamePlay there is a nested class called MyPinAnnotationView. When MyPinAnnotation's method TouchesBegan() gets called, I want to call a method CheckAnswer() from the parent GamePlay.

I do not want to create a new GamePlay instance becau开发者_高级运维se I have variables and instances already set. Can I access the parent in some way? ( Other than event listeners)


The nested class will only be able to reference static members in the parent. If you want to access instance members, you need to get a reference to the instance. The simplest way to do this is to add it as a parameter to the constructor of MyPinAnnotationView like so:

class MyPinAnnotationView
{
  private GamePlay gamePlay;

  public MyPinAnnotationView(GamePlay gamePlay)
  {
    this.gamePlay = gamePlay;
  }

  public void TouchesBegan()
  {
    this.gamePlay.CheckAnswer();
  }
}

When you instantiate MyPinAnnotationView from GamePlay, just do this:

MyPinAnnotation annotation = new MyPinAnnotation(this);


If the methods you want to access are not static, then you will need a reference to the parent object (I commonly pass the parent object reference in as a constructor parameter) in order to access its methods. After all, your child class needs to know which instance of the parent class it is related to.


The easy/quick way would be to keep a reference to the parent class in the child object, make CheckAnswer() public, then it's easy to call the method whenever needed... but you may want to go back and review the design to make sure this is appropriate.


Nested classes should only be utilized by the parent class (see this post). They shouldn't be publicly visible to other classes unless there is a really good reason. Which there isn't.

I would suggest refactoring this. Try moving all the API for GamePlay into the GamePlay class. In other words, TouchesBegan() should be called on the GamePlay class, which then calls into the MyPinAnnotations class.

No one else should know about MyPinAnnotations class - if they need to, then it is indicative of a design failure.

0

精彩评论

暂无评论...
验证码 换一张
取 消