Bagikan melalui


Adding Events to a Class

In an earlier lesson, Closer Look: Understanding Properties, Methods, and Events, you learned that a program can respond to external events, such as a user clicking a button. In this lesson, you will learn how to add your own event to a class.

Declaring and Raising Events

There are two steps that you must take when you add an event to a class. First, you must declare the event, and then you must raise the event. Raising an event means that you are signaling the occurrence of the event. To add an event to a class, you declare it by using the Event statement. This indicates that the object can raise the event you specified. For example, you might want to add an AgeCalculated event to the Persons class that you created in the lesson Modeling a Real-World Object: Creating Your First Class. You can then raise the event in the CalcAge method that you created. After you do this, when the method is called, you can run some additional code as soon as the person's age has been calculated.

Try It!

To add an event to a class

  1. Open the Persons project that you created in the previous lesson. If you did not save it, you will first have to go back to the previous lesson, Adding Methods to a Class, and complete the procedures.

  2. In Solution Explorer, select Persons.vb, and then, on the View menu, click Code.

  3. Add the following code above the property procedures.

    Public Event AgeCalculated(ByVal Age As Integer)
    
  4. In the CalcAge method, replace the existing code with the following code to raise the event.

    Private Function CalcAge(ByVal year As Integer) As Integer 
        Dim Age = My.Computer.Clock.LocalTime.Year - year
        RaiseEvent AgeCalculated(Age)
        CalcAge = My.Computer.Clock.LocalTime.Year - year
    End Function
    
  5. On the File menu, click Save All to save your work.

  6. On the Build menu, click Build Solution to be able to use this class library in other projects.

Next Steps

In this lesson, you learned how to add an event to your class and how to raise the event in a method. You can learn how to write an event handler to run additional code when the event is raised in Closer Look: Handling Events. Then you can learn how to use and test the class that you created in the next lesson.

Next Lesson: Testing a Class

See Also

Tasks

Adding Properties to a Class

Adding Methods to a Class

Other Resources

Programming with Objects: Using Classes

Change History

Date

History

Reason

April 2009

Added a step for building the solution.

Customer feedback.