C#自定义事件处理程序始终返回null

时间:2018-10-11 17:11:21

标签: c# events

我正在创建一个汽车模拟器,其中有一个可以打开引擎的钥匙。引擎通过调用OnEngineTurn方法的回调方法绑定到特定键,该方法引发事件。无论我对EventHandler采取什么措施,我都永远无法使用,因为它始终为null。这是下面的代码。我是C#的新手,所以可以提供任何帮助

public delegate void MyEventHandler(object sender, EventArgs e);

class Engine
{
    public event MyEventHandler EngineTurn;

    //raise the event
    protected virtual void OnEngineTurn(EngineEventArgs e)
    {
         MyEventHandler engineTurn = EngineTurn;

        if (engineTurn != null)
        {
            MessageBox.Show("Hello World");
            engineTurn(this, e);
        }
        else
        {
            MessageBox.Show("Null");
        }
    }

    public CarKey GetNewKey()
    {
        return new CarKey(new KeyCallBack(OnEngineTurn));
    }
}

class EngineEventArgs : EventArgs
{
     public string name { get; set; }

}

delegate void KeyCallBack(EngineEventArgs e);

class CarKey
{
    //we need a way to hook the engine up to the car so we don't crank, but one car with one key
    private KeyCallBack keyCallBack;

    public CarKey(KeyCallBack callBackDelegate)
    {
        this.keyCallBack = new KeyCallBack(callBackDelegate);
    }

    public void TurnTheKey(EngineEventArgs e)
    {
        if (keyCallBack != null)
        {
            MessageBox.Show("A");
            keyCallBack(e);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

carKey = engine1.GetNewKey()应该使用回调方法将特定键绑定到特定引擎,该方法将回调EngineTurn事件。...carKey.TurnTheKey(engineEventArgs)应该引发事件。下面是CarKey的构造函数...我将它放在Engine类中作为回调方法...

    carKey = engine1.GetNewKey(); 
    engineEventArgs = new EngineEventArgs();
    carKey.TurnTheKey(engineEventArgs); 

    public CarKey GetNewKey() 
    {
         return new CarKey(new KeyCallBack(OnEngineTurn));
    }

答案 1 :(得分:0)

解决了问题

class Simulator
{
    private Engine engine = new Engine();
    private Transmission transmission;
    CarKey carKey;

    //public ObservableCollection<string> FanSays { get { return fan.FanSays; } }
    //public ObservableCollection<string> PitcherSays { get { return pitcher.PitcherSays; } }
   // public int Trajectory { get; set; }
    //public int Distance { get; set; }

    public Simulator()
    {
        transmission = new Transmission(engine);
        carKey = engine.GetNewKey();
    }

    public async void StartSimulator()
    {
        EngineEventArgs engineEventArgs = new EngineEventArgs("America!");
        await new MessageDialog("made it inside the start method").ShowAsync();

        carKey.StartTheEngine(engineEventArgs);
    }
}