简体   繁体   中英

In .NET, is it possible to set Events based on calling of a function

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.

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
}

Easy Way:

event EventHandler AnEventHappened;

void AFun()
{
   OnAnEvent();
}

void AnEvent()
{

}

void OnAnEvent()
{
  var tmp = AnEventHappened;
  if(tmp != null) tmp(this, EventArgs.Empty);
}

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.

Hard Way:

Use Aspect Oriented Programming (with something like Castle, or PostSharp) and emit the event that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM