![]() ![]() | ||
You can use the Shared keyword to create class data members. You can use a class data member with the name of the class alone, no object needed. For example, say you have a class named Mathematics, and declare a shared variable named Pi:
Public Class Mathematics Public Shared Pi As Double = 3.1415926535 End Class
Now you can use Pi as a class variable with the Mathematics class directly, no object needed:
integer5 = Mathematics.Pi
Pi is more naturally handled as a constant, of course; you can use Const instead of Shared to create a shared constant that works the same way (except, of course, that you can't assign values to it, because it's a constant):
Public Class Mathematics
Public Const Pi As Double = 3.1415926535
End Class
The reason variables you declare with the Shared keyword are called shared is because they're shared over all instances of the class. For example, take a look at the Shared example on the CD-ROM—in this case, I'm adding a shared data member named Data to the Mathematics class, and each instance of this class will now see the same value stored in Data. To show this, I'll add a method named Increment to the Mathematics class, which increments the value in Data by 1 and returns the new value:
Public Class Mathematics Shared Data As Integer = 0 Public Function Increment() As Integer Data += 1 Return Data End Function End Class
Next, I create two different objects of the Mathematics class, Object1 and Object2. Both of these objects will share the same internal Data member, which you can see by clicking the buttons in this program—one button uses the Increment method of Object1, and the other button uses the Increment method of Object2, but no matter how much you alternate between the buttons, you'll see that the value in Data (which appears in a text box) increments steadily because both objects are working on the same value. Here's what the code looks like:
Dim Object1, Object2 As New Mathematics() Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click TextBox4.Text = "Count = " & Object1.Increment End Sub Private Sub Button3_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button3.Click TextBox4.Text = "Count = " & Object2.Increment End Sub
You can see this program at work in Figure 11.1—the two buttons that use Object1 and Object2 are at the bottom, and the text box that reports the new value stored in the Data member is beneath them. No matter which button you click, the displayed value increments steadily, demonstrating that indeed, both objects are sharing the same value in Data.
Related solution: |
Found on page: |
---|---|
73 |
![]() ![]() | ||