嵌套 C# 类 - 从内部调用外部方法
我有一个名为 GamePlay 的 ViewController 类。在 GamePlay 中有一个名为 MyPinAnnotationView 的嵌套类。当 MyPinAnnotation 的方法 TouchesBegan() 被调用时,我想从父 GamePlay 调用方法 CheckAnswer()。
我不想创建新的 GamePlay 实例,因为我已经设置了变量和实例。我可以通过某种方式访问父级吗? (事件监听器除外)
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 because I have variables and instances already set. Can I access the parent in some way? ( Other than event listeners)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
嵌套类只能引用父类中的静态成员。如果要访问实例成员,则需要获取对该实例的引用。最简单的方法是将其作为参数添加到
MyPinAnnotationView
的构造函数中,如下所示:当您从
GamePlay
实例化MyPinAnnotationView
时,只需这样做: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:When you instantiate
MyPinAnnotationView
fromGamePlay
, just do 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.
简单/快速的方法是在子对象中保留对父类的引用,将
CheckAnswer()
公开,然后在需要时很容易调用该方法......但您可能想要返回并检查设计以确保其合适。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.嵌套类只能由父类使用(请参阅这篇文章)。除非有充分的理由,否则它们不应该对其他类公开可见。那里没有。
我建议重构这个。尝试将
GamePlay
的所有 API 移至GamePlay
类中。换句话说,应该在GamePlay
类上调用TouchesBegan()
,然后调用MyPinAnnotations
类。其他人不应该知道
MyPinAnnotations
类 - 如果他们需要,那么这表明设计失败。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 theGamePlay
class. In other words,TouchesBegan()
should be called on theGamePlay
class, which then calls into theMyPinAnnotations
class.No one else should know about
MyPinAnnotations
class - if they need to, then it is indicative of a design failure.