从引用主类的"子"类调用函数

sti*_*ghy 2 c# design-patterns

我有一些难以解释我的问题,因为我的英语也不好:|!我有以下代码

namespace StighyGames.MyGames {
public class MyGames
{    
...
...
  CarClass myCar = new CarClass(...); 

  Main () {
     MyGames game = MyGames(...);
  }
}
Run Code Online (Sandbox Code Playgroud)

游戏是我的"主要"对象(我的应用程序).

在我的CarClass中我有一些代码......

现在,在myCar(对象)里面我想调用一个函数(一个方法)包含主类MyGames ..方法"GameOver".这,因为,如果我的汽车"爆炸"我将调用GameOver方法.但GameOver方法不能成为myCar的"孩子"......因为GameOver是游戏的一种方法......好吧..希望得到解释,我的问题是:"我不知道如何调用一种方法主要对象类"..

谢谢您的帮助 !

Jam*_*rgy 5

你有几个选择.

1)event在CarClass中创建一个并在MyGames中捕获它.

2)使用a delegate并将函数引用传递给CarClass对象

3)一个属性添加到类型MyGames的CarClass(说所谓的"所有者"),与您共创CarClass后,分配"这个"来了:myCar.Owner=this.因此,您已在CarClass对象中为其创建者创建了一个引用,CarClass中的代码可以直接访问其所有者的方法.

哪个最好取决于具体情况以及如何使用这些对象.事件可能是首选,因为它提供了最大的灵活性.代表的灵活性和效率都低于事件,尽管它们实际上的用途略有不同.(事件实际上是代表的扩展).最后一个可能是最糟糕的形式,一般来说,因为它紧紧地绑定了对象,但它有时间和地点.

这是#1

public class CarClass
{
    // A delegate is a pointer to a function. Events are really a way of late
    // binding delegates, so you need to one of these first to have an event.
    public delegate void ExplodedHandler(CarClass sender);
    // an event is a construct which is used to pass a delegate to another object
    // You create an event based for a delegate, and capture it by
    // assigning the function reference to it after the object is created. 
    public event ExplodedHandler Exploded;
    protected void CarCrash()
    {
       ... do local stuff
       // Make sure ref exists before calling; if its required that something
       //  outside this object always happen as a result of the crash then 
       // handle the other case too (throw an error, e.g.)/
       // See comments below for explanation of the need to copy the event ref
       // before testing against null
       ExplodedHandler tempEvent = Exploded;
       if (tempEvent != null) {
         tempEvent(this);
       } 
    }
}
public class MyGames
{    
...
...
  CarClass myCar = new CarClass(...); 
  myCar.Exploded += new ExplodedHandler(GameOver);
  Main () {
     MyGames game = MyGames(...);
  }
  void GameOver(CarClass sender) {
     // Do stuff

  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为GameOver更像是Game of Car的责任.汽车应该说:"我爆炸了!" (2认同)