Reputation: 22064
Say I have a function named:
void AFun()
{
// body
}
Is it possible to set an event whenever this function is called. Say,
void AnEvent()
{
//body
}
And AnEvent()
will always be called whenever AFun()
is called.
Upvotes: 4
Views: 106
Reputation: 7846
Easy Way:
event EventHandler AnEventHappened;
void AFun()
{
OnAnEvent();
}
void AnEvent()
{
}
void OnAnEvent()
{
var tmp = AnEventHappened;
if(tmp != null) tmp(this, EventArgs.Empty);
}
Upvotes: 1
Reputation: 132994
Yes, it is, but indirectly, if you emit an event in AFun, and AnEvent will listen to that event you'll achieve what you want. Otherwise what you describe is not directly supported
Code sample:
public delegate void EventHandler();
public event EventHandler ev;
public void AFun
{
...do stuff
ev(); //emit
}
//somewhere in the ctor
ev += MyEventHandler;
//finally
void MyEventHandler
{
//handle the event
}
Upvotes: 4
Reputation: 14605
Not as you write it. What you describe is called "Aspect-Oriented Programming" (AOP) and requires compiler support.
Now, there are some extensions to C# and .NET that does AOP by injecting listeners and events into the right places in the code.
Off-topic: in JavaScript you can do this.
Upvotes: 1
Reputation: 7846
Hard Way:
Use Aspect Oriented Programming (with something like Castle, or PostSharp) and emit the event that way.
Upvotes: 0