TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Guest User
Tech Writer
48
12k
How to add an event to a static method in a class?
Aug 2 2019 2:41 PM
I am looking to add an event to a class, and I am using the following answer from stackexchange as a base:
https://stackoverflow.com/questions/85137/how-to-add-an-event-to-a-class
The answer example registers the event every time the frog object jumps.
public event EventHandler Jump;
public void OnJump()
{
EventHandler handler = Jump;
if (null != handler)
handler(this, EventArgs.Empty);
}
Frog frog = new Frog();
frog.Jump += new EventHandler(yourMethod);
private void yourMethod(object s, EventArgs e)
{
Console.WriteLine("Frog has Jumped!");
}
Now this is fine for non-static methods, but the problem is I have a static method in my class, so the "this" keyword won't work. Here is my version of the code:
// In my class file.
public
event
EventHandler Triggered;
public
static
void
Trigger()
{
EventHandler h = Triggered;
if
(h !=
null
)
h(
this
, EventArgs.Empty);
}
// In my main file.
MyClass myObj =
new
MyClass();
myObj.Trigger +=
new
EventHandler(TakeAction);
private
void
TakeAction(
object
o, EventArgs e)
{
Console.WriteLine(
"We made it."
);
}
"this" in line 7 cannot be used due to the static nature of the funciton. How can I modify this code so that it allows this event to be properly registered.
Reply
Answers (
1
)
vb.net need to convert string to integer
I can't pass parameter to method.