VB.Net Tutorial/Collections/IDisposable — различия между версиями

Материал из VB Эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 12:53, 26 мая 2010

IDisposable

Class Point
  Implements IDisposable
 
  Public X = 3
  Public Y = 4
  Sub New(XX As Integer, YY As Integer)
    X = XX
    Y = YY
  End Sub 
  Public Overrides Function ToString() As String
    Return "(" & X & "," & Y & ")"
  End Function
  Public Overridable Overloads Sub Dispose() _
         Implements IDisposable.Dispose
    Console.WriteLine("Point " & Me.ToString() & " disposed of")
  End Sub 
End Class
Class TwoDimension
  Implements IDisposable
  Public First As Point
  Public Second As Point
  Public Sub New()
    First = New Point(1, 2)
    Second = New Point(3,4)
  End Sub
  Public Overrides Function ToString() As String
    Return "(" & First.ToString() & "," & Second.ToString() & ")"
  End Function
  Public Overridable Overloads Sub Dispose() _
                     Implements IDisposable.Dispose
    First.Dispose()
    Second.Dispose()
    First = Nothing
    Second = Nothing
  End Sub
  Protected Overridable Overloads Sub Finalize()
    First.Dispose() 
    Second.Dispose()
    First = Nothing
    Second = Nothing
  End Sub 
End Class
Module Test
  Sub Main()
    Dim P As TwoDimension = New TwoDimension()
    Console.WriteLine("The object is: " & P.ToString())
    P.Dispose()
    P = Nothing
    Console.WriteLine("The object, after disposal is " & P.ToString())
  End Sub
End Module
The object is: ((1,2),(3,4))
Point (1,2) disposed of
Point (3,4) disposed of
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an ob
ject.
   at Test.Main()

Implements IDisposable

public class Test
   
   public Shared Sub Main
        Dim obj As New Named("Dispose ")
        obj.Dispose()
   End Sub
   
End class
    Public Class Named
        Implements IDisposable
        Public Name As String
        Public Sub New(ByVal new_name As String)
            Name = new_name
        End Sub
        Protected Overrides Sub Finalize()
            Dispose()
        End Sub
        Public Sub Dispose() Implements System.IDisposable.Dispose
            Static done_before As Boolean = False
            If done_before Then Exit Sub
            done_before = True
            Console.WriteLine(Name)
        End Sub
    End Class
Dispose