Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Say I have a class named Frog, it looks like:

public class Frog
{
     public int Location { get; set; }
     public int JumpCount { get; set; }


     public void OnJump()
     {
         JumpCount++;
     }

}

I need help with 2 things:

  1. I want to create an event named Jump in the class definition.
  2. I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
113 views
Welcome To Ask or Share your Answers For Others

1 Answer

public event EventHandler Jump;
public void OnJump()
{
    EventHandler handler = Jump;
    if (null != handler) handler(this, EventArgs.Empty);
}

then

Frog frog = new Frog();
frog.Jump += new EventHandler(yourMethod);

private void yourMethod(object s, EventArgs e)
{
     Console.WriteLine("Frog has Jumped!");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...