home *** CD-ROM | disk | FTP | other *** search
- ' this class is used by the TestByrefPassing procedure
- Class SampleClass
- Public Number As Double
- End Class
-
- ' The first version of the Person class demonstrates properties, methods, indexers,
- ' read-only, write-only, and default properties
-
- Class Person
- ' Visual Basic.NET classes can expose Public constants.
- Public Const DefaultPassword As String = "mypwd"
-
- ' Fields visible from outside the class
- Public FirstName As String
- Public LastName As String
-
- ' You can define up to four addresses for this person,
- ' from Address(0) to Address(3).
- Public Address(4) As String
-
- Overridable Function CompleteName(Optional ByVal title As String = "") As String
- ' Use the title, if provided.
- If title <> "" Then CompleteName = title & " "
- ' Append first and last name.
- CompleteName &= FirstName & " " & LastName
- End Function
-
- ' the BirthDate property
-
- Dim m_BirthDate As Date
-
- Property BirthDate() As Date
- Get
- Return m_BirthDate
- End Get
- Set(ByVal Value As Date)
- m_BirthDate = Value
- End Set
- End Property
-
- ' the Spouse property
-
- Private m_Spouse As Person
-
- Property Spouse() As Person
- Get
- Return m_Spouse
- End Get
- Set(ByVal Value As Person)
- m_Spouse = Value
- End Set
- End Property
-
- ' The Age property is read-only.
-
- ReadOnly Property Age() As Integer
- Get
- Return Year(Now) - Year(m_BirthDate)
- End Get
- End Property
-
- ' LoginDate is a write-only property.
-
- Dim m_LoginDate As Date
-
- WriteOnly Property LoginDate() As Date
- Set(ByVal Value As Date)
- m_LoginDate = Value
- End Set
- End Property
-
- ' an example of default property
-
- Dim m_Notes(10) As String
-
- ' The Attachment property takes an Integer argument.
- ' Note that this is also the default property.
-
- Default Property Notes(ByVal index As Integer) As String
- Get
- If index < 0 Or index > UBound(m_Notes) Then
- Throw New IndexOutOfRangeException("Invalid note index")
- End If
- Return m_Notes(index)
- End Get
- Set(ByVal Value As String)
- If index < 0 Or index > UBound(m_Notes) Then
- Throw New IndexOutOfRangeException("Invalid note index")
- End If
- m_Notes(index) = Value
- End Set
- End Property
-
- ' The GotMail event is used to demonstrate event inheritance
-
- Event GotMail(ByVal msgText As String)
-
- Sub NotifyNewMail(ByVal msgText As String)
- ' Let all listeners know that we got mail.
- RaiseEvent GotMail(msgText)
- End Sub
-
- ' The Father, Mother and AreBrothers method are used to
- ' demonstrate shared member inheritance
-
- Public Father As Person
- Public Mother As Person
-
- Shared Function AreBrothers(ByVal p1 As Person, ByVal p2 As Person) As Boolean
- Return (p1.Father Is p2.Father) Or (p1.Mother Is p2.Mother)
- End Function
- End Class
-
- ' This second version of the Person class demonstrates overloaded constructors,
- ' read-only fields, and the Finalize method.
-
- Class Person2
- ' a public read-only field that can be assigned only from inside the constructor.
- Public ReadOnly CreateTime As Date
-
- ' First version of constructors takes first and last name.
-
- Sub New(ByVal firstName As String, ByVal lastName As String)
- Me.FirstName = firstName
- Me.LastName = lastName
- ' Remember when this instance was created.
- CreateTime = Now()
- End Sub
-
- ' Second version takes complete name (e.g. "Joe Doe").
-
- Sub New(ByVal completeName As String)
- Dim i As Integer
- i = InStr(completeName, " ")
- ' Error if there are fewer than two words.
- If i = 0 Then Throw New ArgumentException("Invalid Name")
- ' Initialize main properties.
- Me.FirstName = RTrim(Left(completeName, i - 1))
- Me.LastName = LTrim(Mid(completeName, i + 1))
- ' Remember when this instance was created.
- CreateTime = Now()
- End Sub
-
- ' FirstName and LastName properties
-
- Private m_FirstName As String
- Private m_LastName As String
-
- Property FirstName() As String
- Get
- Return m_FirstName
- End Get
- Set(ByVal Value As String)
- If Value = "" Then
- Throw New ArgumentException("Invalid FirstName property")
- End If
- m_FirstName = Value
- End Set
- End Property
-
- Property LastName() As String
- Get
- Return m_LastName
- End Get
- Set(ByVal Value As String)
- If Value = "" Then
- Throw New ArgumentException("Invalid LastName property")
- End If
- m_LastName = Value
- End Set
- End Property
-
- ' the BirthDate property
-
- Dim m_BirthDate As Date
-
- Property BirthDate() As Date
- Get
- Return m_BirthDate
- End Get
- Set(ByVal Value As Date)
- m_BirthDate = Value
- End Set
- End Property
-
- ' CompleteName property is overridable
-
- Overridable Function CompleteName() As String
- ' Append first and last name.
- Return FirstName & " " & LastName
- End Function
-
- ' the class's Finalize method
-
- Protected Overrides Sub Finalize()
- ' use Debug because the Console object might be finalized at this point.
- Debug.WriteLine("Person " & Me.CompleteName() & " is being destroyed")
- End Sub
-
- End Class
-
- ' This third version of the Person class demonstrates
- ' event trapping from an array of objects.
-
- Class Person3
- Event GotEmail(ByVal p As Person3, ByVal msgText As String)
-
- Public FirstName As String
- Public LastName As String
-
- Sub New(ByVal firstName As String, ByVal lastName As String)
- Me.FirstName = firstName
- Me.LastName = lastName
- End Sub
-
- Function CompleteName() As String
- Return FirstName & " " & LastName
- End Function
-
- ' Send an email to this person.
- ' (In this demo it just raises a GotEmail event.)
- Sub SendEmail(ByVal msgText As String)
- ' Let the client know which object raised the event.
- RaiseEvent GotEmail(Me, msgText)
- End Sub
- End Class
-
- ' This forth version of the Person class demonstrates events that follow
- ' Microsoft's syntax guidelines
-
- Class Person4
- ' some basic properties, methods, and constructors
- Public FirstName As String
- Public LastName As String
-
- Sub New(ByVal firstName As String, ByVal lastName As String)
- Me.FirstName = firstName
- Me.LastName = lastName
- End Sub
-
- Function CompleteName() As String
- Return FirstName & " " & LastName
- End Function
-
- ' support for the Married event
-
- Event Married(ByVal sender As Object, ByVal e As System.EventArgs)
-
- Dim m_Spouse As Person4
-
- Property Spouse() As Person4
- Get
- Return m_Spouse
- End Get
- Set(ByVal Value As Person4)
- ' Raise an event only if this is a different object.
- If Not (m_Spouse Is Value) Then
- m_Spouse = Value
- ' You can use the Empty shared field to return a new
- ' empty EventArgs object
- RaiseEvent Married(Me, EventArgs.Empty)
- End If
- End Set
- End Property
-
- ' support for the GotGift event
-
- Event GotGift(ByVal sender As Object, ByVal e As GotGiftEventArgs)
-
- ' Clients call this method to give a gift to this person.
- Sub GiveGift(ByVal giver As Person4, ByVal description As String)
- ' (In this demo we just raise an event.)
- ' Create a GotGiftEventArgs object on-the-fly.
- RaiseEvent GotGift(Me, New GotGiftEventArgs(giver, description))
- End Sub
-
- End Class
-
- ' auxiliary class used for the Person4's GotGift event.
-
- Class GotGiftEventArgs
- Inherits System.EventArgs
-
- ' The additional fields exposed by this class.
- Public Giver As Person4
- Public GiftDescription As String
-
- ' A convenient constructor
- Sub New(ByVal giver As Person4, ByVal giftDescription As String)
- Me.Giver = giver
- Me.GiftDescription = giftDescription
- End Sub
- End Class
-
- ' a class that demonstrate property values passed byref
-
- Class ValueClass
- Private Value As Double
-
- ' A property that uses the Value field.
- Property DoubleValue() As Double
- Get
- Return Me.Value * 2
- End Get
- Set(ByVal newValue As Double)
- Me.Value = newValue / 2
- End Set
- End Property
- End Class
-
-
- ' The Widget class demonstrates the IDisposable interface.
-
- Class Widget
- Implements IDisposable
-
- Sub Dispose() Implements IDisposable.Dispose
- ' Close files and release other resources here.
- ' ...
- End Sub
- End Class
-
- ' The DataFile class demonstrates the Dispose+Finalize methods working in concert.
- ' The approach used is based on the cleanedUp private variable.
-
- Class DataFile
- Implements IDisposable
-
- ' The file handle
- Private handle As Integer
-
- Sub New(ByVal inputFile As String)
- ' Open a file when the object is created.
- handle = FreeFile()
- FileOpen(handle, inputFile, OpenMode.Input)
- End Sub
-
- Sub Close()
- If handle <> 0 Then
- FileClose(handle)
- handle = 0
- End If
- End Sub
-
- ' True if clean-up code has run already.
- Private disposed As Boolean
-
- Sub Dispose() Implements IDisposable.Dispose
- Console.WriteLine("Dispose method")
- ' Clean up this object by running the Finalize method.
- Finalize()
- End Sub
-
- Protected Overrides Sub Finalize()
- Console.WriteLine("Finalize method")
- ' Run clean-up code only if not done already.
- If Not disposed Then
- ' Close the file if it is still open.
- Close()
- ' Perform other clean-up chores.
- ' ...
- ' Remember that clean-up code has run.
- disposed = True
- End If
- End Sub
- End Class
-
- ' The second version of the DataFile class uses the GC.SuppressFinalize
- ' method for optimized clean-up code.
-
- Class DataFile2
- Implements IDisposable
-
- ' The file handle
- Private handle As Integer
-
- ' Open a file, store its handle.
- Sub Open(ByVal inputFile As String)
- ' Throw an exception if the object has been already disposed.
- If disposed Then Throw New ObjectDisposedException("DataFile2")
- ' Continue with regular operations.
- handle = FreeFile()
- FileOpen(handle, inputFile, OpenMode.Input)
- End Sub
-
- ' Close the file, don't throw an exception if already closed.
- Sub Close()
- ' Throw an exception if the object has been already disposed.
- If disposed Then Throw New ObjectDisposedException("DataFile2")
- ' Continue with regular operations.
- If handle <> 0 Then
- FileClose(handle)
- handle = 0
- End If
- End Sub
-
- ' This private variable is True if the object has been disposed.
- Dim disposed As Boolean
-
- Sub Dispose() Implements IDisposable.Dispose
- Debug.WriteLine("Dispose method")
- ' Execute the code that does the clean up.
- Dispose(True)
- ' Let the CLR know that Finalize doesn't have to be called.
- GC.SuppressFinalize(Me)
- End Sub
-
- Protected Overrides Sub Finalize()
- Debug.WriteLine("Finalize method")
- ' Execute the code that does the clean up.
- Dispose(False)
- End Sub
-
- ' This procedure is where the actual cleanup occurs.
- Protected Overridable Sub Dispose(ByVal disposing As Boolean)
- ' Exit now if the object has been already disposed.
- If disposed Then Exit Sub
-
- If disposing Then
- ' The object is being disposed, not finalized.
- ' It is safe to access other objects (other than the base
- ' object) only from inside this block.
- End If
-
- ' Perform clean up chores that have to be executed in either case.
- Close()
-
- ' Remember that the object has been disposed.
- disposed = True
- End Sub
- End Class
-
- ' The PrimeNumbers class demonstrates weakly-referenced objects.
-
- Class PrimeNumbers
- ' IsPrime(n) contains True if n is prime, False otherwise
- Public IsPrime() As Boolean
-
- ' The constructor evaluates "primeness" for the first N integers.
- Sub New(ByVal maxPrimeNumber As Integer)
- ReDim IsPrime(maxPrimeNumber)
- Dim i, j As Integer
-
- ' For debugging purposes
- Console.WriteLine("Initializing PrimeNumbers")
-
- ' A rather inefficient algorithm (hey, it's just a demo).
- ' Start assuming that all numbers are prime.
- For i = 1 To maxPrimeNumber
- IsPrime(i) = True
- Next
-
- ' Next, visit all items, starting at IsPrime(2).
- For i = 2 To maxPrimeNumber
- ' If this number is prime, then all its multiple aren't prime.
- If IsPrime(i) Then
- For j = i * 2 To maxPrimeNumber Step i
- IsPrime(j) = False
- Next
- End If
- Next
- End Sub
- End Class
-
- ' The Logger class demonstrates WithEvents and AddHandler keywords
-
- Class Logger
- Event LogAction(ByVal actionName As String)
-
- Sub OpenFile()
- RaiseEvent LogAction("OpenFile")
- End Sub
-
- Sub ReadData()
- RaiseEvent LogAction("ReadData")
- End Sub
-
- Sub CloseFile()
- RaiseEvent LogAction("CloseFile")
- End Sub
-
- Protected Overrides Sub Finalize()
- RaiseEvent LogAction("Finalize")
- End Sub
- End Class
-
- ' The Invoice class demonstrates shared members.
-
- Class Invoice
- ' This variable holds the number of instances created so far.
- Shared InstanceCount As Integer
-
- ' A unique ID for this instance.
- Public ReadOnly Id As Long
-
- Sub New()
- ' Increment number of created instances.
- InstanceCount += 1
- ' Use the current count as the ID for this instance.
- Id = InstanceCount
- ' ...
- End Sub
- End Class
-
- ' The SerialPort class demonstrates the use of shared fields and methods
-
- Class SerialPort
- Implements IDisposable
-
- ' This array is shared by all instances of the class.
- ' (This examples assumes that 4 ports are available.)
- Public Shared AllocatedPorts(3) As Boolean
-
- ' Return the number of the first available serial port.
- Shared Function GetAvailablePort() As Short
- Dim i As Short
- For i = 0 To 3
- If AllocatedPorts(i) = False Then
- ' This port is still available.
- GetAvailablePort = i
- Exit For
- End If
- ' Return รป1 if no port is available.
- GetAvailablePort = -1
- Next
- End Function
-
- ' The serial port used by this instance (in the range 0-3).
- Public ReadOnly Port As Short
-
- Sub New()
- Port = GetAvailablePort()
- ' throw a (generic) exception if no port is available
- If Port < 0 Then Throw New Exception()
- ' Mark the port as unavailable.
- AllocatedPorts(Port) = True
- End Sub
-
- ' Mark the port as available when this instance is destroyed.
- Sub Dispose() Implements IDisposable.Dispose
- AllocatedPorts(Port) = False
- End Sub
- End Class
-
- ' The Triangle class demonstrates using shared members
-
- Class Triangle
- Shared Event InvalidTriangle(ByVal side1 As Double, ByVal side2 As Double, ByVal side3 As Double)
- Event DummyEvent()
-
- Shared Function GetPerimeter(ByVal side1 As Double, _
- ByVal side2 As Double, ByVal side3 As Double) As Double
- If side1 < side2 + side3 And side1 > Math.Abs(side2 - side3) Then
- Return side1 + side2 + side3
- Else
- ' Pass Nothing when the event is raised from inside
- ' a shared method.
- RaiseEvent InvalidTriangle(side1, side2, side3)
- End If
- End Function
-
- Shared Function GetArea(ByVal side1 As Double, _
- ByVal side2 As Double, ByVal side3 As Double) As Double
-
- If side1 < side2 + side3 And side1 > Math.Abs(side2 - side3) Then
- ' First, evaluate half of the perimeter.
- Dim halfP As Double = (side1 + side2 + side3) / 2
- ' Then apply the Heron formula.
- Return (halfP * (halfP - side1) * (halfP - side2) * (halfP - side3)) ^ 0.5
- Else
- ' Pass Nothing when the event is raised from inside
- ' a shared method.
- RaiseEvent InvalidTriangle(side1, side2, side3)
- End If
- End Function
-
- ' The tree sides
- Public Side1 As Double
- Public Side2 As Double
- Public Side3 As Double
-
- ' The Perimeter instance property
- ReadOnly Property Perimeter() As Double
- Get
- If Side1 < Side2 + Side3 And Side1 > Math.Abs(Side2 - Side3) Then
- Return Side1 + Side2 + Side3
- Else
- RaiseEvent InvalidTriangle(Side1, Side2, Side3)
- End If
- End Get
- End Property
-
- ' The Area instance property
- ReadOnly Property Area() As Double
- Get
- If Side1 < Side2 + Side3 And Side1 > Math.Abs(Side2 - Side3) Then
- ' First, evaluate half of the perimeter.
- Dim halfP As Double = (Side1 + Side2 + Side3) / 2
- ' Then apply the Heron formula.
- Return (halfP * (halfP - Side1) * (halfP - Side2) * (halfP - Side3)) ^ 0.5
- Else
- RaiseEvent InvalidTriangle(Side1, Side2, Side3)
- End If
- End Get
- End Property
-
- End Class
-
- ' The FileLogger class demonstrates shared constructors
-
- Class FileLogger
- Shared FileHandle As Integer
-
- ' a readonly shared member
- Public Shared ReadOnly StartExecutionTime As Date = Now()
- Public Shared ReadOnly InitialDir As String
-
- ' The shared constructor
- Shared Sub New()
- ' Open the log file before the first object from
- ' this class is instantiated.
- FileHandle = FreeFile()
- FileOpen(FileHandle, "C:\data.log", OpenMode.Output)
-
- InitialDir = System.IO.Directory.GetCurrentDirectory
- End Sub
-
- ' a shared method that closes the log file
- Shared Sub Close()
- FileClose(FileHandle)
- End Sub
-
- Sub New()
- ' Here goes the initialization code for a specific instance.
- ' ...
- End Sub
-
- Sub Log(ByVal Text As String)
- PrintLine(FileHandle, Text)
- End Sub
- End Class
-
-
-
-