event
keywordEventHandler
delegatepublic class Publisher
{
public event EventHandler SampleEvent;
// Wrap the event in a protected virtual method
// to enable derived classes to raise the event.
protected virtual void OnSampleEvent()
{
// Raise the event in a thread-safe manner using the ?. operator.
SampleEvent?.Invoke(this);
}
}
Events can only be invoked (i.e., raised) from within the class (or derived classes) or struct where they're declared (the publisher class)
public class Publisher
{
public event EventHandler SampleEvent;
protected virtual void OnSampleEvent()
{
SampleEvent?.Invoke(this);
}
}
class Program
{
static void Main()
{
var pub = new Publisher();
pub.OnSampleEvent(); //
Works fine
// pub.SampleEvent(); //
Not allowed!
}
}
public class Publisher
{
public event EventHandler SampleEvent;
protected virtual void OnSampleEvent()
{
SampleEvent?.Invoke(this);
}
}
class Program
{
static void Main()
{
var pub = new Publisher();
pub.SampleEvent +=
() => Console.WriteLine("Sample event!");
pub.OnSampleEvent();
}
}
public class Publisher
{
public delegate void SampleEventHandler(object sender);
// Declare the event.
public event SampleEventHandler SampleEvent;
protected virtual void OnSampleEvent()
{
SampleEvent?.Invoke(this);
}
}
public class SampleEventArgs
{
public SampleEventArgs(string text) { Text = text; }
public string Text { get; } // readonly
}
public class Publisher
{
public delegate void SampleEventHandler(object sender, SampleEventArgs e);
public event SampleEventHandler SampleEvent;
protected virtual void RaiseSampleEvent()
{
SampleEvent?.Invoke(this, new SampleEventArgs("Hello"));
}
}
public delegate void GameOverHandler();
class Game
{
public event GameOverHandler GameOver;
protected virtual void OnGameOver()
{
GameOver?.Invoke(this);
}
}
...
class Program
{
static void Main()
{
var game = new Game();
Sound gameOverSound;
Window gameOverScreen;
game.GameOver += gameOverSound.Play;
game.GameOver += gameOverScreen.Show;
}
}
GameOverHandler
)event
keyword (GameOVer
)Create a console application for controlling a plant treatment system with three methods that print the following outputs:
Method | Output |
---|---|
void ReleaseWater() |
Releasing water... |
void ReleaseFertilizer() |
Releasing fertilizer... |
void IncreaseTemperature() |
Increasing temperature... |
run
to execute all the methods that are onHint: you can just use switch-case for defining which method should be added to the delegate
Here's an example console input & output: