[英]C# Custom Event Handler is always returning null
I am creating a car simulator where I have a key that turns on an engine. 我正在创建一个汽车模拟器,其中有一个可以打开引擎的钥匙。 The engine is tied to a specific key with a callback method which calls the
OnEngineTurn
method which raises the event. 引擎通过回调方法绑定到特定键,该回调方法调用引发事件的
OnEngineTurn
方法。 No matter what I do to the EventHandler
, I it never works because it always is null. 无论我对
EventHandler
做什么,我都永远无法使用,因为它始终为null。 Here is the code below. 这是下面的代码。 I am relatively new to C# so any help is appreciated
我是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);
}
}
}
carKey = engine1.GetNewKey() should tie a specific key to a specific engine with a callback method that calls back to the EngineTurn Event.... carKey.TurnTheKey(engineEventArgs) is suppose to raise the event.... Below is the constructor for CarKey... I have it inside the Engine class for the callback method... 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));
}
Solved the problem 解决了问题
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.