In .NET, you can set events based on a function call

Say I have a function called:

void AFun() { // body } 

Is it possible to set an event whenever this function is called. Let's say

 void AnEvent() { //body } 

And AnEvent() will always be called whenever AFun() called.

+4
source share
4 answers

Yes, it is, but indirectly, if you release an event in AFun, and AnEvent listens for this event, you will achieve what you want. Otherwise, what you are describing is not directly supported.

Code example:

 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 } 
+4
source

A simple way:

 event EventHandler AnEventHappened; void AFun() { OnAnEvent(); } void AnEvent() { } void OnAnEvent() { var tmp = AnEventHappened; if(tmp != null) tmp(this, EventArgs.Empty); } 
+1
source

Not the way you write it. What you are describing is called Aspect Oriented Programming (AOP) and requires compiler support.

Now there are some extensions for C # and .NET that do AOP by inserting listeners and events into the right places in the code.

Off topic: in JavaScript you can do this.

+1
source

Hard way:

Use aspect-oriented programming (with something like Castle or PostSharp) and highlight the event this way.

0
source

Source: https://habr.com/ru/post/1345839/


All Articles