home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / setup / vbnet / 04 class fundamentals / classesdemo / classes.vb < prev    next >
Encoding:
Text File  |  2002-03-16  |  18.8 KB  |  645 lines

  1. ' this class is used by the TestByrefPassing procedure
  2. Class SampleClass
  3.     Public Number As Double
  4. End Class
  5.  
  6. ' The first version of the Person class demonstrates properties, methods, indexers,
  7. ' read-only, write-only, and default properties
  8.  
  9. Class Person
  10.     ' Visual Basic.NET classes can expose Public constants.
  11.     Public Const DefaultPassword As String = "mypwd"
  12.  
  13.     ' Fields visible from outside the class
  14.     Public FirstName As String
  15.     Public LastName As String
  16.  
  17.     ' You can define up to four addresses for this person,
  18.     ' from Address(0) to Address(3).
  19.     Public Address(4) As String
  20.  
  21.     Overridable Function CompleteName(Optional ByVal title As String = "") As String
  22.         ' Use the title, if provided.
  23.         If title <> "" Then CompleteName = title & " "
  24.         ' Append first and last name.
  25.         CompleteName &= FirstName & " " & LastName
  26.     End Function
  27.  
  28.     ' the BirthDate property
  29.  
  30.     Dim m_BirthDate As Date
  31.  
  32.     Property BirthDate() As Date
  33.         Get
  34.             Return m_BirthDate
  35.         End Get
  36.         Set(ByVal Value As Date)
  37.             m_BirthDate = Value
  38.         End Set
  39.     End Property
  40.  
  41.     ' the Spouse property
  42.  
  43.     Private m_Spouse As Person
  44.  
  45.     Property Spouse() As Person
  46.         Get
  47.             Return m_Spouse
  48.         End Get
  49.         Set(ByVal Value As Person)
  50.             m_Spouse = Value
  51.         End Set
  52.     End Property
  53.  
  54.     ' The Age property is read-only.
  55.  
  56.     ReadOnly Property Age() As Integer
  57.         Get
  58.             Return Year(Now) - Year(m_BirthDate)
  59.         End Get
  60.     End Property
  61.  
  62.     ' LoginDate is a write-only property.
  63.  
  64.     Dim m_LoginDate As Date
  65.  
  66.     WriteOnly Property LoginDate() As Date
  67.         Set(ByVal Value As Date)
  68.             m_LoginDate = Value
  69.         End Set
  70.     End Property
  71.  
  72.     ' an example of default property
  73.  
  74.     Dim m_Notes(10) As String
  75.  
  76.     ' The Attachment property takes an Integer argument.
  77.     ' Note that this is also the default property.
  78.  
  79.     Default Property Notes(ByVal index As Integer) As String
  80.         Get
  81.             If index < 0 Or index > UBound(m_Notes) Then
  82.                 Throw New IndexOutOfRangeException("Invalid note index")
  83.             End If
  84.             Return m_Notes(index)
  85.         End Get
  86.         Set(ByVal Value As String)
  87.             If index < 0 Or index > UBound(m_Notes) Then
  88.                 Throw New IndexOutOfRangeException("Invalid note index")
  89.             End If
  90.             m_Notes(index) = Value
  91.         End Set
  92.     End Property
  93.  
  94.     ' The GotMail event is used to demonstrate event inheritance
  95.  
  96.     Event GotMail(ByVal msgText As String)
  97.  
  98.     Sub NotifyNewMail(ByVal msgText As String)
  99.         ' Let all listeners know that we got mail.
  100.         RaiseEvent GotMail(msgText)
  101.     End Sub
  102.  
  103.     ' The Father, Mother and AreBrothers method are used to 
  104.     ' demonstrate shared member inheritance
  105.  
  106.     Public Father As Person
  107.     Public Mother As Person
  108.  
  109.     Shared Function AreBrothers(ByVal p1 As Person, ByVal p2 As Person) As Boolean
  110.         Return (p1.Father Is p2.Father) Or (p1.Mother Is p2.Mother)
  111.     End Function
  112. End Class
  113.  
  114. ' This second version of the Person class demonstrates overloaded constructors, 
  115. ' read-only fields, and the Finalize method.
  116.  
  117. Class Person2
  118.     ' a public read-only field that can be assigned only from inside the constructor.
  119.     Public ReadOnly CreateTime As Date
  120.  
  121.     ' First version of constructors takes first and last name.
  122.  
  123.     Sub New(ByVal firstName As String, ByVal lastName As String)
  124.         Me.FirstName = firstName
  125.         Me.LastName = lastName
  126.         ' Remember when this instance was created.
  127.         CreateTime = Now()
  128.     End Sub
  129.  
  130.     ' Second version takes complete name (e.g. "Joe Doe").
  131.  
  132.     Sub New(ByVal completeName As String)
  133.         Dim i As Integer
  134.         i = InStr(completeName, " ")
  135.         ' Error if there are fewer than two words.
  136.         If i = 0 Then Throw New ArgumentException("Invalid Name")
  137.         ' Initialize main properties.
  138.         Me.FirstName = RTrim(Left(completeName, i - 1))
  139.         Me.LastName = LTrim(Mid(completeName, i + 1))
  140.         ' Remember when this instance was created.
  141.         CreateTime = Now()
  142.     End Sub
  143.  
  144.     ' FirstName and LastName properties
  145.  
  146.     Private m_FirstName As String
  147.     Private m_LastName As String
  148.  
  149.     Property FirstName() As String
  150.         Get
  151.             Return m_FirstName
  152.         End Get
  153.         Set(ByVal Value As String)
  154.             If Value = "" Then
  155.                 Throw New ArgumentException("Invalid FirstName property")
  156.             End If
  157.             m_FirstName = Value
  158.         End Set
  159.     End Property
  160.  
  161.     Property LastName() As String
  162.         Get
  163.             Return m_LastName
  164.         End Get
  165.         Set(ByVal Value As String)
  166.             If Value = "" Then
  167.                 Throw New ArgumentException("Invalid LastName property")
  168.             End If
  169.             m_LastName = Value
  170.         End Set
  171.     End Property
  172.  
  173.     ' the BirthDate property
  174.  
  175.     Dim m_BirthDate As Date
  176.  
  177.     Property BirthDate() As Date
  178.         Get
  179.             Return m_BirthDate
  180.         End Get
  181.         Set(ByVal Value As Date)
  182.             m_BirthDate = Value
  183.         End Set
  184.     End Property
  185.  
  186.     ' CompleteName property is overridable
  187.  
  188.     Overridable Function CompleteName() As String
  189.         ' Append first and last name.
  190.         Return FirstName & " " & LastName
  191.     End Function
  192.  
  193.     ' the class's Finalize method
  194.  
  195.     Protected Overrides Sub Finalize()
  196.         ' use Debug because the Console object might be finalized at this point.
  197.         Debug.WriteLine("Person " & Me.CompleteName() & " is being destroyed")
  198.     End Sub
  199.  
  200. End Class
  201.  
  202. ' This third version of the Person class demonstrates 
  203. ' event trapping from an array of objects.
  204.  
  205. Class Person3
  206.     Event GotEmail(ByVal p As Person3, ByVal msgText As String)
  207.  
  208.     Public FirstName As String
  209.     Public LastName As String
  210.  
  211.     Sub New(ByVal firstName As String, ByVal lastName As String)
  212.         Me.FirstName = firstName
  213.         Me.LastName = lastName
  214.     End Sub
  215.  
  216.     Function CompleteName() As String
  217.         Return FirstName & " " & LastName
  218.     End Function
  219.  
  220.     ' Send an email to this person.
  221.     ' (In this demo it just raises a GotEmail event.)
  222.     Sub SendEmail(ByVal msgText As String)
  223.         ' Let the client know which object raised the event.
  224.         RaiseEvent GotEmail(Me, msgText)
  225.     End Sub
  226. End Class
  227.  
  228. ' This forth version of the Person class demonstrates events that follow
  229. ' Microsoft's syntax guidelines 
  230.  
  231. Class Person4
  232.     ' some basic properties, methods, and constructors
  233.     Public FirstName As String
  234.     Public LastName As String
  235.  
  236.     Sub New(ByVal firstName As String, ByVal lastName As String)
  237.         Me.FirstName = firstName
  238.         Me.LastName = lastName
  239.     End Sub
  240.  
  241.     Function CompleteName() As String
  242.         Return FirstName & " " & LastName
  243.     End Function
  244.  
  245.     ' support for the Married event
  246.  
  247.     Event Married(ByVal sender As Object, ByVal e As System.EventArgs)
  248.  
  249.     Dim m_Spouse As Person4
  250.  
  251.     Property Spouse() As Person4
  252.         Get
  253.             Return m_Spouse
  254.         End Get
  255.         Set(ByVal Value As Person4)
  256.             ' Raise an event only if this is a different object.
  257.             If Not (m_Spouse Is Value) Then
  258.                 m_Spouse = Value
  259.                 ' You can use the Empty shared field to return a new
  260.                 ' empty EventArgs object
  261.                 RaiseEvent Married(Me, EventArgs.Empty)
  262.             End If
  263.         End Set
  264.     End Property
  265.  
  266.     ' support for the GotGift event
  267.  
  268.     Event GotGift(ByVal sender As Object, ByVal e As GotGiftEventArgs)
  269.  
  270.     ' Clients call this method to give a gift to this person.
  271.     Sub GiveGift(ByVal giver As Person4, ByVal description As String)
  272.         ' (In this demo we just raise an event.)
  273.         ' Create a GotGiftEventArgs object on-the-fly.
  274.         RaiseEvent GotGift(Me, New GotGiftEventArgs(giver, description))
  275.     End Sub
  276.  
  277. End Class
  278.  
  279. ' auxiliary class used for the Person4's GotGift event.
  280.  
  281. Class GotGiftEventArgs
  282.     Inherits System.EventArgs
  283.  
  284.     ' The additional fields exposed by this class.
  285.     Public Giver As Person4
  286.     Public GiftDescription As String
  287.  
  288.     ' A convenient constructor
  289.     Sub New(ByVal giver As Person4, ByVal giftDescription As String)
  290.         Me.Giver = giver
  291.         Me.GiftDescription = giftDescription
  292.     End Sub
  293. End Class
  294.  
  295. ' a class that demonstrate property values passed byref
  296.  
  297. Class ValueClass
  298.     Private Value As Double
  299.  
  300.     ' A property that uses the Value field.
  301.     Property DoubleValue() As Double
  302.         Get
  303.             Return Me.Value * 2
  304.         End Get
  305.         Set(ByVal newValue As Double)
  306.             Me.Value = newValue / 2
  307.         End Set
  308.     End Property
  309. End Class
  310.  
  311.  
  312. ' The Widget class demonstrates the IDisposable interface.
  313.  
  314. Class Widget
  315.     Implements IDisposable
  316.  
  317.     Sub Dispose() Implements IDisposable.Dispose
  318.         ' Close files and release other resources here.
  319.         ' ...
  320.     End Sub
  321. End Class
  322.  
  323. ' The DataFile class demonstrates the Dispose+Finalize methods working in concert.
  324. ' The approach used is based on the cleanedUp private variable.
  325.  
  326. Class DataFile
  327.     Implements IDisposable
  328.  
  329.     ' The file handle
  330.     Private handle As Integer
  331.  
  332.     Sub New(ByVal inputFile As String)
  333.         ' Open a file when the object is created.
  334.         handle = FreeFile()
  335.         FileOpen(handle, inputFile, OpenMode.Input)
  336.     End Sub
  337.  
  338.     Sub Close()
  339.         If handle <> 0 Then
  340.             FileClose(handle)
  341.             handle = 0
  342.         End If
  343.     End Sub
  344.  
  345.     ' True if clean-up code has run already.
  346.     Private disposed As Boolean
  347.  
  348.     Sub Dispose() Implements IDisposable.Dispose
  349.         Console.WriteLine("Dispose method")
  350.         ' Clean up this object by running the Finalize method.
  351.         Finalize()
  352.     End Sub
  353.  
  354.     Protected Overrides Sub Finalize()
  355.         Console.WriteLine("Finalize method")
  356.         ' Run clean-up code only if not done already.
  357.         If Not disposed Then
  358.             ' Close the file if it is still open.
  359.             Close()
  360.             ' Perform other clean-up chores.
  361.             ' ...
  362.             ' Remember that clean-up code has run.
  363.             disposed = True
  364.         End If
  365.     End Sub
  366. End Class
  367.  
  368. ' The second version of the DataFile class uses the GC.SuppressFinalize 
  369. ' method for optimized clean-up code.
  370.  
  371. Class DataFile2
  372.     Implements IDisposable
  373.  
  374.     ' The file handle
  375.     Private handle As Integer
  376.  
  377.     ' Open a file, store its handle.
  378.     Sub Open(ByVal inputFile As String)
  379.         ' Throw an exception if the object has been already disposed.
  380.         If disposed Then Throw New ObjectDisposedException("DataFile2")
  381.         ' Continue with regular operations.
  382.         handle = FreeFile()
  383.         FileOpen(handle, inputFile, OpenMode.Input)
  384.     End Sub
  385.  
  386.     ' Close the file, don't throw an exception if already closed. 
  387.     Sub Close()
  388.         ' Throw an exception if the object has been already disposed.
  389.         If disposed Then Throw New ObjectDisposedException("DataFile2")
  390.         ' Continue with regular operations.
  391.         If handle <> 0 Then
  392.             FileClose(handle)
  393.             handle = 0
  394.         End If
  395.     End Sub
  396.  
  397.     ' This private variable is True if the object has been disposed.
  398.     Dim disposed As Boolean
  399.  
  400.     Sub Dispose() Implements IDisposable.Dispose
  401.         Debug.WriteLine("Dispose method")
  402.         ' Execute the code that does the clean up.
  403.         Dispose(True)
  404.         ' Let the CLR know that Finalize doesn't have to be called.
  405.         GC.SuppressFinalize(Me)
  406.     End Sub
  407.  
  408.     Protected Overrides Sub Finalize()
  409.         Debug.WriteLine("Finalize method")
  410.         ' Execute the code that does the clean up.
  411.         Dispose(False)
  412.     End Sub
  413.  
  414.     ' This procedure is where the actual cleanup occurs.
  415.     Protected Overridable Sub Dispose(ByVal disposing As Boolean)
  416.         ' Exit now if the object has been already disposed.
  417.         If disposed Then Exit Sub
  418.  
  419.         If disposing Then
  420.             ' The object is being disposed, not finalized. 
  421.             ' It is safe to access other objects (other than the base
  422.             ' object) only from inside this block.
  423.         End If
  424.  
  425.         ' Perform clean up chores that have to be executed in either case.
  426.         Close()
  427.  
  428.         ' Remember that the object has been disposed.
  429.         disposed = True
  430.     End Sub
  431. End Class
  432.  
  433. ' The PrimeNumbers class demonstrates weakly-referenced objects.
  434.  
  435. Class PrimeNumbers
  436.     ' IsPrime(n) contains True if n is prime, False otherwise
  437.     Public IsPrime() As Boolean
  438.  
  439.     ' The constructor evaluates "primeness" for the first N integers.
  440.     Sub New(ByVal maxPrimeNumber As Integer)
  441.         ReDim IsPrime(maxPrimeNumber)
  442.         Dim i, j As Integer
  443.  
  444.         ' For debugging purposes
  445.         Console.WriteLine("Initializing PrimeNumbers")
  446.  
  447.         ' A rather inefficient algorithm (hey, it's just a demo).
  448.         ' Start assuming that all numbers are prime.
  449.         For i = 1 To maxPrimeNumber
  450.             IsPrime(i) = True
  451.         Next
  452.  
  453.         ' Next, visit all items, starting at IsPrime(2).
  454.         For i = 2 To maxPrimeNumber
  455.             ' If this number is prime, then all its multiple aren't prime.
  456.             If IsPrime(i) Then
  457.                 For j = i * 2 To maxPrimeNumber Step i
  458.                     IsPrime(j) = False
  459.                 Next
  460.             End If
  461.         Next
  462.     End Sub
  463. End Class
  464.  
  465. ' The Logger class demonstrates WithEvents and AddHandler keywords
  466.  
  467. Class Logger
  468.     Event LogAction(ByVal actionName As String)
  469.  
  470.     Sub OpenFile()
  471.         RaiseEvent LogAction("OpenFile")
  472.     End Sub
  473.  
  474.     Sub ReadData()
  475.         RaiseEvent LogAction("ReadData")
  476.     End Sub
  477.  
  478.     Sub CloseFile()
  479.         RaiseEvent LogAction("CloseFile")
  480.     End Sub
  481.  
  482.     Protected Overrides Sub Finalize()
  483.         RaiseEvent LogAction("Finalize")
  484.     End Sub
  485. End Class
  486.  
  487. ' The Invoice class demonstrates shared members.
  488.  
  489. Class Invoice
  490.     ' This variable holds the number of instances created so far.
  491.     Shared InstanceCount As Integer
  492.  
  493.     ' A unique ID for this instance.
  494.     Public ReadOnly Id As Long
  495.  
  496.     Sub New()
  497.         ' Increment number of created instances.
  498.         InstanceCount += 1
  499.         ' Use the current count as the ID for this instance.
  500.         Id = InstanceCount
  501.         ' ...
  502.     End Sub
  503. End Class
  504.  
  505. ' The SerialPort class demonstrates the use of shared fields and methods
  506.  
  507. Class SerialPort
  508.     Implements IDisposable
  509.  
  510.     ' This array is shared by all instances of the class.
  511.     ' (This examples assumes that 4 ports are available.)
  512.     Public Shared AllocatedPorts(3) As Boolean
  513.  
  514.     ' Return the number of the first available serial port.    
  515.     Shared Function GetAvailablePort() As Short
  516.         Dim i As Short
  517.         For i = 0 To 3
  518.             If AllocatedPorts(i) = False Then
  519.                 ' This port is still available.
  520.                 GetAvailablePort = i
  521.                 Exit For
  522.             End If
  523.             ' Return รป1 if no port is available.
  524.             GetAvailablePort = -1
  525.         Next
  526.     End Function
  527.  
  528.     ' The serial port used by this instance (in the range 0-3).
  529.     Public ReadOnly Port As Short
  530.  
  531.     Sub New()
  532.         Port = GetAvailablePort()
  533.         ' throw a (generic) exception if no port is available
  534.         If Port < 0 Then Throw New Exception()
  535.         ' Mark the port as unavailable.
  536.         AllocatedPorts(Port) = True
  537.     End Sub
  538.  
  539.     ' Mark the port as available when this instance is destroyed.
  540.     Sub Dispose() Implements IDisposable.Dispose
  541.         AllocatedPorts(Port) = False
  542.     End Sub
  543. End Class
  544.  
  545. ' The Triangle class demonstrates using shared members
  546.  
  547. Class Triangle
  548.     Shared Event InvalidTriangle(ByVal side1 As Double, ByVal side2 As Double, ByVal side3 As Double)
  549.     Event DummyEvent()
  550.  
  551.     Shared Function GetPerimeter(ByVal side1 As Double, _
  552.         ByVal side2 As Double, ByVal side3 As Double) As Double
  553.         If side1 < side2 + side3 And side1 > Math.Abs(side2 - side3) Then
  554.             Return side1 + side2 + side3
  555.         Else
  556.             ' Pass Nothing when the event is raised from inside 
  557.             ' a shared method.
  558.             RaiseEvent InvalidTriangle(side1, side2, side3)
  559.         End If
  560.     End Function
  561.  
  562.     Shared Function GetArea(ByVal side1 As Double, _
  563.         ByVal side2 As Double, ByVal side3 As Double) As Double
  564.  
  565.         If side1 < side2 + side3 And side1 > Math.Abs(side2 - side3) Then
  566.             ' First, evaluate half of the perimeter.
  567.             Dim halfP As Double = (side1 + side2 + side3) / 2
  568.             ' Then apply the Heron formula.
  569.             Return (halfP * (halfP - side1) * (halfP - side2) * (halfP - side3)) ^ 0.5
  570.         Else
  571.             ' Pass Nothing when the event is raised from inside 
  572.             ' a shared method.
  573.             RaiseEvent InvalidTriangle(side1, side2, side3)
  574.         End If
  575.     End Function
  576.  
  577.     ' The tree sides
  578.     Public Side1 As Double
  579.     Public Side2 As Double
  580.     Public Side3 As Double
  581.  
  582.     ' The Perimeter instance property
  583.     ReadOnly Property Perimeter() As Double
  584.         Get
  585.             If Side1 < Side2 + Side3 And Side1 > Math.Abs(Side2 - Side3) Then
  586.                 Return Side1 + Side2 + Side3
  587.             Else
  588.                 RaiseEvent InvalidTriangle(Side1, Side2, Side3)
  589.             End If
  590.         End Get
  591.     End Property
  592.  
  593.     ' The Area instance property
  594.     ReadOnly Property Area() As Double
  595.         Get
  596.             If Side1 < Side2 + Side3 And Side1 > Math.Abs(Side2 - Side3) Then
  597.                 ' First, evaluate half of the perimeter.
  598.                 Dim halfP As Double = (Side1 + Side2 + Side3) / 2
  599.                 ' Then apply the Heron formula.
  600.                 Return (halfP * (halfP - Side1) * (halfP - Side2) * (halfP - Side3)) ^ 0.5
  601.             Else
  602.                 RaiseEvent InvalidTriangle(Side1, Side2, Side3)
  603.             End If
  604.         End Get
  605.     End Property
  606.  
  607. End Class
  608.  
  609. ' The FileLogger class demonstrates shared constructors
  610.  
  611. Class FileLogger
  612.     Shared FileHandle As Integer
  613.  
  614.     ' a readonly shared member
  615.     Public Shared ReadOnly StartExecutionTime As Date = Now()
  616.     Public Shared ReadOnly InitialDir As String
  617.  
  618.     ' The shared constructor
  619.     Shared Sub New()
  620.         ' Open the log file before the first object from
  621.         ' this class is instantiated.
  622.         FileHandle = FreeFile()
  623.         FileOpen(FileHandle, "C:\data.log", OpenMode.Output)
  624.  
  625.         InitialDir = System.IO.Directory.GetCurrentDirectory
  626.     End Sub
  627.  
  628.     ' a shared method that closes the log file
  629.     Shared Sub Close()
  630.         FileClose(FileHandle)
  631.     End Sub
  632.  
  633.     Sub New()
  634.         ' Here goes the initialization code for a specific instance.
  635.         ' ...
  636.     End Sub
  637.  
  638.     Sub Log(ByVal Text As String)
  639.         PrintLine(FileHandle, Text)
  640.     End Sub
  641. End Class
  642.  
  643.  
  644.  
  645.